数据库无法连接

时间:2014-01-29 07:21:41

标签: java database connection database-connection

我有一个数据库项目,我试图从netbeabs连接数据库,我创建了一个连接类;

public class Global {

public static Connection createConnection() {
    Connection conn = null;
    System.out.println("Checking if Driver is registered with DriverManager.");
try{
        Class.forName("org.postgresql.Driver");
} catch (ClassNotFoundException e){
        System.out.println("Couldn't find the driver!");
        System.out.println("exit.");
        System.exit(1);
}
System.out.println("make a connection.");
try{
        conn = DriverManager.getConnection("jdbc:postgresql://localhost:5432/ydb_lib", "postgres", "postgres");
        System.out.println("Success.");
} catch(SQLException e){
        System.out.println("Couldn't connect: exit.");
        System.exit(1);
    }
    return conn;
}

}

我用这个方法调用这个类;

      Connection c = Global.createConnection();

运行程序后,输出为;

      Checking if Driver is registered with DriverManager.
      Couldn't find the driver!
      exit.

我无法看到问题,我的用户名,密码,驱动程序名称,数据库名称是对的,所以您认为可能是什么问题?

3 个答案:

答案 0 :(得分:0)

您的数据库驱动程序jar不在类路径中。

请打印出您的例外,而不是忽略它们并打印出您自己的错误消息。这可以为您节省大量的麻烦。

答案 1 :(得分:0)

org.postgresql.Driver类不在您的类路径中。

答案 2 :(得分:0)

问题可能是由于项目运行时无法找到posrtgesql JDBC驱动程序。

所以在类库的路径中添加jar。 通过以下URL获取PostgreSQL JDBC驱动程序:http://jdbc.postgresql.org/download.html

相关问题