2015-06-21 147 views
2

我正在运行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); 
    } 
+0

不知'JDBC:'是区分大小写的。 (我猜这不是问题,但试试吧......) – immibis

+0

是的..它的工作! – Gautam

回答

1

我赶紧试了你的代码,首先得到了同样的错误:

纠正为: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://本地主机: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(); 
    } 
+0

谢谢。我只是将Jdbc转换为小例子,并且工作正常! – Gautam

相关问题