微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

无法使用Java访问第二个MYSQL数据库

如何解决无法使用Java访问第二个MYSQL数据库

| 连接到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数据库的先前连接。     

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。