JDBC获取表名以及表相关字段名

    public static void main(String[] args) throws Exception {
        String url = "jdbc:mysql:;
        String user = "root";
        String password = "root";
        Class.forName("com.mysql.jdbc.Driver");
        Connection connection = DriverManager.getConnection(url, user, password);
        DatabaseMetaData metaData = connection.getMetaData();
        ResultSet tables = metaData.getTables(null, null, null, null);
        List<String> tableList = new ArrayList<String>();
        while (tables.next()) {
            System.out.println(tables.getString("TABLE_NAME"));
            String tableName = tables.getString("TABLE_NAME");
            ResultSet columns = metaData.getColumns(null, "%", tableName, "%");
            List<String> columnList = new ArrayList<>(20);
            while (columns.next()) {
                System.out.println(columns.getString("COLUMN_NAME"));
            }
        }
  

        connection.close();

    }
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
你可以使用Java中的JDBC API来获取数据库中的表名字段名。以下是获取表名字段名的示例代码: ```java import java.sql.*; public class TableAndColumnNames { public static void main(String[] args) throws SQLException { // Replace the values below with your own database details String url = "jdbc:mysql://localhost:3306/mydatabase"; String username = "myusername"; String password = "mypassword"; // Connect to the database Connection connection = DriverManager.getConnection(url, username, password); // Get the metadata of the database DatabaseMetaData metaData = connection.getMetaData(); // Get the table names String[] tableTypes = {"TABLE"}; ResultSet tables = metaData.getTables(null, null, "%", tableTypes); System.out.println("Table names:"); while (tables.next()) { String tableName = tables.getString("TABLE_NAME"); System.out.println(tableName); // Get the column names for each table ResultSet columns = metaData.getColumns(null, null, tableName, "%"); System.out.println("Column names:"); while (columns.next()) { String columnName = columns.getString("COLUMN_NAME"); System.out.println(columnName); } System.out.println(); } // Close the database connection connection.close(); } } ``` 在上面的示例代码中,我们首先连接到数据库,然后获取数据库的元数据。我们然后使用`getTables()`方法获取所有的名称,并使用`getColumns()`方法获取每个的所有列名称。注意,`getTables()`和`getColumns()`方法都需要指定表名的模式,我们在这里使用`%`来示匹配所有表名和列名。最后,我们关闭数据库连接。 请注意,这只是一个示例代码,你需要将其修改为适合自己的数据库类型和结构的代码。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值