问题描述
|
连接到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`
解决方法
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驱动程序在类路径上。让我们知道您看到的异常消息,以便我们更好地解决您的问题。
, 可能太简单了,但是您没有说在建立与db2数据库的新连接之前是否已关闭与db1数据库的先前连接。