我正在运行 Netbeans 8.0.2。我正在学习 JDBC 并希望将其连接到 PostgreSQL 数据库。我查找了所有可能的答案,但没有答案使它起作用。
我还在左侧菜单中选择了库作为 PostgreSQL JDBC Driver -postgresql-9.2-1002.jdbc4.jar
显示的错误是:
SQL exception occuredjava.sql.SQLException: No suitable driver found for Jdbc:postgresql://localhost:5432/postgres
代码如下:
try {
Class.forName("org.postgresql.Driver");
}
catch(ClassNotFoundException e) {
System.out.println("Class not found "+ e);
}
try {
Connection con = DriverManager.getConnection
("Jdbc:postgresql://localhost:5432/postgres","postgres",
"gautam");
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery
("SELECT * FROM role");
System.out.println("id name");
while (rs.next()) {
int id = rs.getInt("id");
String name = rs.getString("name");
System.out.println(id+" "+name);
}
}
catch(SQLException e){
System.out.println("SQL exception occured" + e);
}
最佳答案
我很快尝试了你的代码,首先得到了同样的错误:
更正为: DriverManager.getConnection("jdbc:postgresql://localhost:5432/postgres", "postgres","gautam");
它有效。
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class NewClass {
public void initialize() {
try {
Class.forName("org.postgresql.Driver");
} catch (ClassNotFoundException e) {
System.out.println("Class not found " + e);
}
try {
Connection con = DriverManager.getConnection("jdbc:postgresql://localhost:5432/postgres", "postgres","gautam");
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM role");
System.out.println("id name");
while (rs.next()) {
int id = rs.getInt("id");
String name = rs.getString("name");
System.out.println(id + " " + name);
}
} catch (SQLException e) {
System.out.println("SQL exception occured" + e);
}
}
public static void main(String[] args) {
new NewClass().initialize();
}
}
DriverManager 询问注册到它的每个驱动程序是否可以读取 url:“jdbc:postgresql://localhost:5432/postgres”。
第一个返回的驱动程序使用 true
。
在您的情况下,没有驱动程序返回 true。
返回 true 或 false 的驱动程序方法是 acceptsURL("jdbc:postgresql://localhost:5432/postgres")
您可以使用以下方法进行测试:
try {
Enumeration<Driver> drivers = DriverManager.getDrivers();
while (drivers.hasMoreElements()) {
Driver nextElement = drivers.nextElement();
JOptionPane.showMessageDialog(null, nextElement.acceptsURL("jdbc:postgresql://localhost:5432/postgres"));
JOptionPane.showMessageDialog(null, nextElement.acceptsURL("Jdbc:postgresql://localhost:5432/postgres"));
}
} catch (SQLException e) {
e.printStackTrace();
}
关于java - 如何解决 'No suitable driver found'错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30964016/