2015-06-21 104 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

相關問題