Java:连接到psql数据库会引发错误(ClassNotFoundException)

时间:2018-12-14 16:22:12

标签: java database database-connection psql

我是Java的新手,我尝试在代码和错误的详细信息下方连接到本地PSql数据库,但未成功。

我有2个文件:DbContract.java和TestConnection.java,我正在使用Eclipse。

DbContract.java

package dbcontract.db;

public interface DbContract {

    public static final String HOST = "jdbc:postgresql://localhost:5432/";
    public static final String DB_NAME = "db_notespesa";
    public static final String USERNAME = "postgres";
    public static final String PASSWORD = "";
}

TestConnection.java

package dbcontract;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

import dbcontract.db.DbContract;

public class TestConnection {

    public static void main(String[] args) {
        try {
            Class.forName("org.postgresql.Driver");
            Connection conn = DriverManager.getConnection(
                    DbContract.HOST+DbContract.DB_NAME,
                    DbContract.USERNAME,
                    DbContract.PASSWORD);
            System.out.println("DB connected");

        } catch (ClassNotFoundException | SQLException e) {
            e.printStackTrace();
        }
    }
}

错误:

java.lang.ClassNotFoundException: org.postgresql.Driver
    at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:583)
    at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:178)
    at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:521)
    at java.base/java.lang.Class.forName0(Native Method)
    at java.base/java.lang.Class.forName(Class.java:315)
    at TestConnection.main(TestConnection.java:13)

1 个答案:

答案 0 :(得分:1)

您需要为Postgress驱动程序添加依赖项,如错误说明所述,如果您使用的是maven,只需将其添加到pom.xml中:

router.get("/", (req, res) => {
  let db = new sqlLite.Database(path.resolve("data.db"), (err) => {
   if (err) {
    console.error(err.message);
   }
   console.log("Connected to the chinook database.");
  });
  db.get(`SELECT * FROM data WHERE key = '${req.query.data}'`, (err, row) => {
   db.close((err) => {
     if (err) {
      console.error(err.message);
     }
     console.log("Close the database connection.");
   });
   res.json(row);
  });
});

按照注释中提到的Mark更新了版本,这是maven repo上所有版本的链接: https://mvnrepository.com/artifact/org.postgresql/postgresql