【发布时间】:2017-10-08 14:32:55
【问题描述】:
我是Java 的新手并正在开发一个Swing 应用程序,所以这个项目完全取决于JDBC,它对我来说非常大,我正在尝试创建一个Connection Class 和在我的整个项目中使用它。
我已经写了一个代码来获取connecton
package sab;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class ConnectionManager {
private static String url = "jdbc:h2:~/test";
private static String driverName = "org.h2.Driver";
private static String username = "sa";
private static String password = "";
private static Connection connection;
private static String urlstring;
public static Connection getConnection() {
try {
Class.forName(driverName);
try {
connection = DriverManager.getConnection(url, username, password);
} catch (SQLException ex) {
// log an exception. fro example:
System.out.println("Failed to create the database connection.");
}
} catch (ClassNotFoundException ex) {
// log an exception. for example:
System.out.println("Driver not found.");
}
return connection;
}
public static void main(String[] args) {
getConnection();
}
}
但是当我尝试测试连接时,它会显示
Failed to create the database connection.
Driver not found.
我不知道做错了什么,请帮忙
【问题讨论】:
-
向我们展示你的
SQLExceptionex.printStackTrace()的堆栈跟踪 -
如果您在 catch 块中包含
ex.printStackTrace(),它应该会告诉您连接失败的确切原因。调试时检查堆栈跟踪非常重要。
标签: java jdbc connection database-connection