我有一个简单的Java程序
import java.sql.*;
public class Main {
public static void main(String[] args) {
String SQL_SELECT = "select * from accesspoint";
try {
Connection conn = DriverManager.getConnection(
"jdbc:postgresql://192.168.1.2:19000/database",
"user",
"pass");
PreparedStatement preparedStatement = conn.prepareStatement(SQL_SELECT);
ResultSet resultSet = preparedStatement.executeQuery();
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
}
我使用
javac Main.java
构建它。
当我尝试使用 java Main
运行它时,我得到一个明显的异常
Exception in thread "main" java.lang.RuntimeException:
java.sql.SQLException: No suitable driver found for
jdbc:postgresql://192.168.1.2:19000/database
问题是如何解决?我在同一目录中有 postgresql-42.6.0.jar,所以我尝试使用 java -cp 但出现错误:
$ java -cp "/home/mst/test_conn/postgresql-42.6.0.jar" Main
Error: Could not find or load main class Main
另外,我尝试设置 CLASSPATH 变量并得到与上面相同的错误。 我做错了什么?
要指定类路径,包括当前目录 (.) 和 PostgreSQL JDBC 驱动程序 JAR 文件的位置,请在 java 命令中使用 -cp 选项。执行命令如下:
java -cp .:postgresql-42.6.0.jar Main
希望它有效:)