我正在使用本地数据库在JDBC,MySql中学习基本的CRUD,问题是对于每个Crud方法,我必须指定要使用的模式。是否有任何方法可以放置一次?当我将使用h2数据库对其进行测试时,这将成为一个问题。
` 公共类DbConnection实现ConnectionProvider {
private MysqlDataSource datasource = new MysqlDataSource();
/* FileNotFoundException, setUseSSL= false not working
*TODO: fix fileNotFoundException , properties password and username error
*/
public DbConnection() {
Properties properties = new Properties();
try {
//datasource.setUseSSL(false);
properties.load(new FileInputStream("src/main/java/ConnectionSource.properties"));
} catch (IOException e) {
e.printStackTrace();
}
String password = properties.getProperty("password");
String serverName = properties.getProperty("host");
String user = properties.getProperty("user");
datasource.setPassword(password);
datasource.setUser(user);
datasource.setServerName(serverName);
}
//For different Databases and users
public DbConnection(String password, String user, String serverName){
datasource.setPassword(password);
datasource.setUser(user);
datasource.setServerName(serverName);
}
@Override
public Connection getConnection() throws IOException, SQLException, ClassNotFoundException {
return datasource.getConnection();
}
}
The Provider:
公用接口ConnectionProvider {
Connection getConnection() throws IOException, SQLException, ClassNotFoundException;
}`
我在哪里指定: `public void createTableSubjects(MysqlDataSource dataSource){
FileReader file = new FileReader();
file.readFromFileSubjects();
String query = "CREATE TABLE IF NOT EXISTS " + file.getItemFromList(1) + "( " +
" " + file.getItemFromList(2) + " " + file.getItemFromList(22) + " unique not null," +
" " + file.getItemFromList(3) + " " + file.getItemFromList(22) + " default 'null'," +
" " + file.getItemFromList(4) + " " + file.getItemFromList(22) + " default 'null'," +
" " + file.getItemFromList(5) + " " + file.getItemFromList(22) + " default 'null'," +
" " + file.getItemFromList(6) + " " + file.getItemFromList(22) + " default 'null'," +
" " + file.getItemFromList(7) + " " + file.getItemFromList(22) + " default 'null'," +
" PRIMARY KEY (" + file.getItemFromList(2) + ")" +
")";
/**Så ingen poeng med å bruke preparedStatement her**/
try (Connection con = dataSource.getConnection()) {
Statement stmt = con.createStatement();
stmt.executeUpdate("USE Time_edit"); //TODO: how to specify once only?
stmt.executeUpdate(query);
System.out.println("New Table 'Subjects' created");
} catch (SQLException e) {
System.out.println("Failed to create Table 'Subjects' \n" + e.getMessage());
e.printStackTrace();
}
}
`
答案 0 :(得分:1)
在数据源上设置数据库名称:
datasource.setPassword(password);
datasource.setUser(user);
datasource.setServerName(serverName);
datasource.setDatabaseName("Time_edit");