2013-02-27 29 views
0

我一直試圖在netbeans中使用JDBC進行練習,但我遇到了一個小問題,現在我加載了一個驅動程序,建立了一個到SQL的連接,但對於一些原因我SQL語句不工作,我會很高興,如果有人可以跟我實例化SQL語句時出錯(Java)(JDBC)

public void dbTest() { 
    try { 
     Class.forName(
       "com.mysql.jdbc.Driver").newInstance(); 
    } catch (InstantiationException | 
      IllegalAccessException | 
      ClassNotFoundException e) { 
    } 

    try (Connection connection = DriverManager.getConnection(
      "jdbc:mysql://localhost:3306/", "root", "explore"); 
      Statement statement = (Statement) connection.createStatement()) { 
     String query = "select first_name, last_name" 
       + " from sakila.customer " 
       + "where address_id < 10"; 
     try (ResultSet resultset = 
       statement.executeQuery(query)) { 
      while (resultset.next()) { 
       String firstName = 
         resultset.getString("first_name"); 
       String lastName = 
         resultset.getString("last_name"); 
       System.out.println(firstName + " " + lastName); 
      } 
     } 
    } catch (SQLException e) { 
    } 
} 

承擔這行代碼是造成我的麻煩

Statement statement = (Statement) connection.createStatement() 

謝謝!

+3

當你說它給你帶來麻煩時你是什麼意思?它拋出一個異常?它不會讓你編譯? – 2013-02-27 16:24:27

+1

很可能你沒有使用'java.sql.Statement'。你可能正在使用'java.beans.Statement' – PermGenError 2013-02-27 16:25:39

+0

@KevinD它不會讓我編譯 – 2013-02-27 16:31:47

回答

0

由於大多數評論指出,您應該使用java.sql.Statement而不是java.beans.Statement

我注意到你的代碼的另一件事是你正在查詢,你沒有指定從哪個數據庫執行這些操作,這將導致你到SQLException。因此,您需要將網址字符串從"jdbc:mysql://localhost:3306/"更改爲"jdbc:mysql://localhost:3306/database_name"

希望這會有所幫助。