数据字典是一个记录数据库对象信息的文档,包括表、列、索引、触发器等的详细描述。在 Java 中,我们可以使用 JDBC 来连接数据库并操作数据,以下是一个简单的示例,实现了创建一个数据字典的数据库表,并向其中插入一些数据。

数据库脚本:

CREATE TABLE `dictionary` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(50) NOT NULL,
  `type` varchar(20) DEFAULT NULL,
  `description` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

代码实现:

import java.sql.*;

public class Dictionary {
    static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
    static final String DB_URL = "jdbc:mysql://localhost:3306/test";
    static final String USER = "root";
    static final String PASS = "password";

    public static void main(String[] args) {
        Connection conn = null;
        Statement stmt = null;

        try {
            Class.forName(JDBC_DRIVER);
            conn = DriverManager.getConnection(DB_URL, USER, PASS);
            stmt = conn.createStatement();

            // 插入数据
            String sql = "INSERT INTO dictionary (name, type, description) VALUES ('user', 'table', '用户表')";
            stmt.executeUpdate(sql);

            sql = "INSERT INTO dictionary (name, type, description) VALUES ('id', 'column', '用户ID')";
            stmt.executeUpdate(sql);

            sql = "INSERT INTO dictionary (name, type, description) VALUES ('name', 'column', '用户名')";
            stmt.executeUpdate(sql);

            // 查询数据
            sql = "SELECT id, name, type, description FROM dictionary";
            ResultSet rs = stmt.executeQuery(sql);

            // 输出结果
            while (rs.next()) {
                int id = rs.getInt('id');
                String name = rs.getString('name');
                String type = rs.getString('type');
                String description = rs.getString('description');

                System.out.println("ID: " + id);
                System.out.println("Name: " + name);
                System.out.println("Type: " + type);
                System.out.println("Description: " + description);
            }

            rs.close();
            stmt.close();
            conn.close();
        } catch (SQLException se) {
            se.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (stmt != null) stmt.close();
            } catch (SQLException se2) {
            }
            try {
                if (conn != null) conn.close();
            } catch (SQLException se) {
                se.printStackTrace();
            }
        }
    }
}

在这个示例中,我们首先创建了一个名为“dictionary”的数据表,并定义了三个字段:id、name和description。然后,我们使用 JDBC 连接到数据库,并通过 Statement 执行 SQL 语句向表中插入了三条数据。最后,我们查询了整个表,并输出了查询结果。
Java 数据字典数据库脚本和代码示例 - 如何用 JDBC 创建和管理数据库信息

原文地址: https://www.cveoy.top/t/topic/m8Ig 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录