在连接到java中的第二个MYSQL数据库时是否有特定要注意的事项?
我查询一个数据库db1
就好了,但当我切换到重复的数据库db2
并运行相同的查询时
当在eclipse中运行时,程序只是说“终止”而没有输出。
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection con = DriverManager.getConnection
("jdbc:mysql://localhost/db2", "root", "password");
con.setReadOnly(true);
Statement stmt = con.createStatement();
ResultSet res = stmt.executeQuery("query that worked for db1");
//then do stuff with res that printed out the grabbed
//results successfully for db1`
答案 0 :(得分:2)
Connection connection = null;
try {
// Load the JDBC driver
Class.forName("com.mysql.jdbc.Driver");
// Create a connection to the database
String serverName = "localhost";
String mydatabase = "db2";
String url = "jdbc:mysql://" + serverName + "/" + mydatabase; // JDBC url
String username = "root";
String password = "password";
connection = DriverManager.getConnection(url, username, password);
} catch (ClassNotFoundException e) {
// Could not find the database driver
} catch (SQLException e) {
// Could not connect to the database
} finally {
System.out.println("Closing the connection.");
if (connection != null) try { connection.close(); } catch (SQLException ignore) {}
}
捕获异常并确保Mysql驱动程序位于类路径中。请告诉我们您看到的异常消息,以便我们能够更好地解决您的问题。
答案 1 :(得分:-2)
可能过于简单,但是在建立新的db2数据库之前,你没有说过你是否已经关闭了之前与db1数据库的连接。