我是 JDBC 新手,我正在尝试为课程开发一个项目。 我们应该创建一个数据库和该数据库的关系。 如果数据库或关系已经存在,我们应该打印一条消息通知用户。 我不太确定该怎么做。 这就是我到目前为止的方法:
public static void createDatabase() throws Exception {
String createString =
"CREATE DATABASE IF NOT EXISTS companydb";
Statement stmt = null;
try {
String driver = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://localhost:3306/?autoReconnect=true&useSSL=false";
String username = "username";
String password = "password";
Class.forName(driver);
Connection con = DriverManager.getConnection(url, username, password);
stmt = con.createStatement();
stmt.executeUpdate(createString);
System.out.println("Database created.");
} catch (Exception e) {
System.out.println(e);
} finally {
if (stmt != null) { stmt.close();
}
}
}
创建员工表(尚未创建所有值,只是测试运行):
public static void createEmployeeTable() throws Exception {
String createString =
"create table if not exists employee" + "(Fname char(32) NOT NULL, " +
PRIMARY KEY(Fname)";
Statement stmt = null;
try {
Connection con = getConnection();
stmt = con.createStatement();
stmt.executeUpdate(createString);
System.out.println("Employee table created.");
} catch (Exception e) {
System.out.println(e);
} finally {
if (stmt != null) { stmt.close(); }
}
}
我还意识到创建这样的表可能不是建立关系的最有效方法,但这只是目前正在进行的工作。
无论数据库和关系/表是否已经存在,它都会输出相同的输出:
Database created.
Connected to database.
Employee table created.
Connected to database.
Department table created.
Connected to database.
Project table created.
Connected to database.
Works_On table created.
将代码分解为两个步骤。