我有一个非常简单的Java程序,它连接到PostgreSQL数据库,通过特定的命名模式查找是否有任何数据库。当我找到它们时,我试图通过Java JDBC代码删除它们。 Java代码在我手动运行时工作正常,但我想要实现的是通过批处理文件自动化这个Java调用。
任何人都可以对此嗤之以鼻吗?我一直在努力寻找解决方案,这令人沮丧。
我的Java代码:
public class CreateBatchToCleanNamedDBs {
public static void main(String[] args) {
Connection connection = null;
BufferedReader input = null;
try {
String line;
RandomAccessFile batchFile = new RandomAccessFile("C:/batch.sql", "rw");
Class.forName("org.postgresql.Driver");
connection = DriverManager.getConnection("jdbc:postgresql://localhost:5432/postgres", "postgres", "Welcome12!");
Statement stmt = connection.createStatement();
ResultSet rs = stmt.executeQuery("select datname from pg_database where datname like 'sample_db%';");
while (rs.next()) {
batchFile.writeBytes("DROP DATABASE " + rs.getString("datname") + ";\n");
System.out.println(rs.getString("datname"));
}
Process batchProcess = Runtime.getRuntime().exec("C:/Program Files/PostgreSQL/9.5/bin/psql -h localhost -U postgres -f C:/batch.sql");
input = new BufferedReader(new InputStreamReader(batchProcess.getInputStream()));
if(batchFile.length()!= 0) {
while ((line = input.readLine()) != null) {
System.out.println(line);
}
}
batchFile.close();
} catch(Exception exception) {
System.out.println("Exception caught: " + exception);
exception.printStackTrace();
} finally {
try {
connection.close();
} catch (SQLException sqlexception) {
sqlexception.printStackTrace();
}
}
}
}
我的批处理文件脚本:
@echo off
setlocal
if not defined JAVA_HOME goto :NoJavaFound
"%JAVA_HOME%\bin\java.exe" -jar "%~dp0\deletedb.jar;%~dp0\postgresql-9.4.1207.jar;" connect.postgresql.CreateBatchToCleanNamedDBs
goto :end
:NoJavaFound
echo JAVA_HOME environment variable is not set.
goto :end
:end
endlocal
我同时拥有jar文件(我的Java代码,如上所示)和桌面上的批处理脚本文件(同一文件夹)并尝试运行 - 但我得到了NullPointerException
,因为我的java代码缺少PostgreSQL jdbc驱动程序。我试图以多种方式将其作为参数添加,但没有任何作用。
错误详情:
C:\Users\pavan>C:\Users\pbonda\Desktop\deletedb.bat
Exception caught: java.lang.ClassNotFoundException: org.postgresql.Driver
java.lang.ClassNotFoundException: org.postgresql.Driver
at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:264)
at connect.postgresql.CreateBatchToCleanNamedDBs.main(CreateBatchToCleanNamedDBs.java:20)
Exception in thread "main" java.lang.NullPointerException
at connect.postgresql.CreateBatchToCleanNamedDBs.main(CreateBatchToCleanNamedDBs.java:45)
答案 0 :(得分:3)
使用可执行jar调用java时,将忽略提供给java命令的类路径。
你应该:
"%JAVA_HOME%\bin\java.exe" -cp "%~dp0\deletedb.jar;%~dp0\postgresql-9.4.1207.jar;" connect.postgresql.CreateBatchToCleanNamedDBs
)java -jar
执行jar。见Oracle doc 答案 1 :(得分:1)
尝试:
"%JAVA_HOME%\bin\java.exe" -cp "%~dp0\postgresql-9.4.1207.jar;%~dp0\deletedb.jar" connect.postgresql.CreateBatchToCleanNamedDBs