postgresql 使用www.example.com从Django运行java jarsubprocess.run

dwthyt8l  于 2023-06-22  发布在  PostgreSQL
关注(0)|答案(1)|浏览(128)

我为一件很简单的事发疯了。
我有一个jar程序,需要从Django的数据库中读取数据。它将db连接url作为参数。当我在命令行中运行时,一切正常:

C:\Dev\mcl>java -jar mcl.jar "jdbc:postgresql://<IP:PORT>/DBName?user=<user>&password=<pwd>"

但是当我在Django中从线程运行它时,它找不到postgres驱动程序。我用途:

result = subprocess.run(['java.exe', '-jar', 'mcl.jar', '"jdbc:postgresql://<IP:PORT>/DBName?user=<user>&password=<pwd>"'], cwd=r'C:\\Dev\\mcl', capture_output=True, shell=True, text=True)

它不起作用,我得到:找不到适用于“jdbc:postgresql://IP:PORT/DBName?user=&password=”的驱动程序
我尝试了很多方法,比如在mcl.jar中嵌入postgres jar,在www.example.com调用中更改参数subprocess.run,但都不起作用。
在java中,我尝试了带和不带

Class.forName("org.postgresql.Driver");

Java代码是:

try {
                mConn = DriverManager.getConnection(mURL);
                mConn.setAutoCommit(true);
            } catch (SQLException ex) {
                System.err.println("Database connection error: " + ex.getLocalizedMessage());
                mConn = null;
            }

Django环境必须有一些特定的东西,但是什么呢?

b5buobof

b5buobof1#

最后设法使它工作,从一个文件加载配置,并首先创建驱动程序,然后使用它打开连接。下面是一个例子:

protected boolean loadConfiguration() {
        Properties properties = new Properties();

        try (FileInputStream fileInputStream = new FileInputStream(CONFIG_FILE)) {
            properties.load(fileInputStream);
            mURL = properties.getProperty("url");
            mUser = properties.getProperty("user");
            mPassword = properties.getProperty("password");
            return connect() != null;
        } catch (IOException e) {
            WTrace.errTrace("Error reading config: " + e.getLocalizedMessage());
        }
        return connect() != null;
    }
    
    protected Connection connect() {
        if (mConn == null) {
            try {
                Class.forName("org.postgresql.Driver");
            } catch (ClassNotFoundException ex) {
                System.err.println("Cannot load DB driver: " + ex.getLocalizedMessage());
            }
            Properties info = new Properties(); 
            info.put("user", mUser); 
            info.put("password", mPassword);

            Driver driver;
            try {
                driver = DriverManager.getDriver(mURL);
            } catch (SQLException ex) {
                System.err.println("Get DB driver error: " + ex.getLocalizedMessage());
                return null;
            }
            try {
                mConn = driver.connect(mURL, info);
            } catch (SQLException ex) {
                System.err.println("Connect error: " + ex.getLocalizedMessage());
            }
            System.err.println("Connection: " + mConn == null ? "fail" : "OK");
        }
        return mConn;
    }

相关问题