java语言如何动态循环创建mysql数据库基本表,可以实现吗?

2024-12-25 19:28:04
推荐回答(2个)
回答1:

下面是一个简单的连接MySQL数据库,并操作数据库表的例子:

import java.sql.*;

public class TestMysql {

public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
try {
//加载驱动
Class.forName("com.mysql.jdbc.Driver");
//创建连接
conn = DriverManager
.getConnection("jdbc:mysql://localhost/bbs?user=用户名&password=密码");
stmt = conn.createStatement();
rs = stmt.executeQuery("select * from user");
while (rs.next()) {
String user = rs.getString(1);
String password = rs.getString(2);
System.out.println("用户名:" + user + "," +" 密码:" + password );
}

} catch (ClassNotFoundException ex) {
ex.printStackTrace();
} catch (SQLException ex) {
ex.printStackTrace();
} finally {
try {
if (rs != null) {
rs.close();
rs = null;
}
if (stmt != null) {
stmt.close();
stmt = null;
}
if (conn != null) {
conn.close();
conn = null;
}

} catch (SQLException e) {
e.printStackTrace();
}
}
}

}

当然前提是要把MySQL的连接驱动JAR文件添加到工程里

回答2:

实现是当然可以的
文本文件内,定义SQL或字段名+类别+长度(需要的话)
读进来后,就按 CREATE TABLE 这样套