Java获取MySQL表字段类型_java获取mysql数据库表、字段、字段类型、字段注释
时间: 2023-10-20 17:05:28 浏览: 50
可以通过JDBC连接MySQL数据库,使用以下代码获取表字段类型和注释:
```java
import java.sql.*;
public class MySQLTableInfo {
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 {
// Register JDBC driver
Class.forName(JDBC_DRIVER);
// Open a connection
System.out.println("Connecting to database...");
conn = DriverManager.getConnection(DB_URL, USER, PASS);
// Execute a query
System.out.println("Creating statement...");
stmt = conn.createStatement();
String sql;
sql = "SELECT COLUMN_NAME, DATA_TYPE, COLUMN_COMMENT FROM information_schema.columns WHERE table_schema = 'test' AND table_name = 'my_table'";
ResultSet rs = stmt.executeQuery(sql);
// Extract data from result set
while (rs.next()) {
// Retrieve by column name
String column_name = rs.getString("COLUMN_NAME");
String data_type = rs.getString("DATA_TYPE");
String column_comment = rs.getString("COLUMN_COMMENT");
// Display values
System.out.print("Column Name: " + column_name);
System.out.print(", Data Type: " + data_type);
System.out.println(", Column Comment: " + column_comment);
}
// Clean-up environment
rs.close();
stmt.close();
conn.close();
} catch (SQLException se) {
// Handle errors for JDBC
se.printStackTrace();
} catch (Exception e) {
// Handle errors for Class.forName
e.printStackTrace();
} finally {
// finally block used to close resources
try {
if (stmt != null) stmt.close();
} catch (SQLException se2) {
} // nothing we can do
try {
if (conn != null) conn.close();
} catch (SQLException se) {
se.printStackTrace();
} // end finally try
} // end try
System.out.println("Goodbye!");
} // end main
} // end MySQLTableInfo class
```
在上面的代码中,需要替换以下变量:
- `DB_URL`:数据库连接URL
- `USER`:用户名
- `PASS`:密码
- `table_schema`:数据库名
- `table_name`:表名
运行以上代码,即可获取MySQL表字段类型和注释。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)