2011-11-23 74 views
-5

我正在學習如何從一本書中的java連接到mysql,但我得到一個錯誤,第一行..包聲明。我完全按照書中的內容複製了代碼(以下給出),並且我已正確下載所有內容,請幫助!謝謝!java mysql快速

package mysql; 
import java.sql.*; 

    public class test { 
    Connection connection; 
    private void displaySQLErrors(SQLException e) { 
    System.out.println("SQLException: " + e.getMessage()); 
    System.out.println("SQLState:  " + e.getSQLState()); 
    System.out.println("VendorError: " + e.getErrorCode()); 

} 

public test() { 
    try { 
     Class.forName("com.mysql.jdbc.Driver").newInstance(); 
    } 
    catch (SQLException e) { 
     System.err.println("Unable to find and load driver"); 
     System.exit(1); 
    } 
} 

public void connectToDB() { 
    try { 
     connection = DriverManager.getConnection(
       "jdbc:mysql://localhost/accounts?user=&password="); 
    } 
    catch(SQLException e){ 
     displaySQLErrors(e); 
    } 
} 

public void executeSQL() { 
    try{ 
     Statement statement = connection.createStatement(); 

     ResultSet rs = statement.executeQuery(
       "SELECT * FROM acc_acc"); 

     while (rs.next()) { 
      System.out.println(rs.getString(1)); 
     } 

     rs.close(); 
     statement.close(); 
     connection.close(); 
    } 
    catch(SQLException e) { 
     displaySQLErrors(e); 
    } 
} 

public static void main(String[] args){ 
    test test1 = new test(); 

    test1.connectToDB(); 
    test1.executeSQL(); 
} 
} 
+6

而這是什麼錯誤?細節? –

回答

1

如果您的包裝聲明有錯誤,可能是因爲您沒有包裝在正確的包裝中!

如果您在代碼中聲明瞭package mysql;,那麼您需要將它放在源代碼樹中的mysql文件夾中。

+0

我確實擁有它在正確的包裝..感謝你我想出來 – user1062436

0

你應該寫

Class.forName("com.mysql.jdbc.Driver"); 

加載驅動程序和

connection = DriverManager.getConnection("jdbc:mysql://localhost/accounts","yourUsername","yourPassword"); 
+0

這不再是必要的,除非你是在1.6以前的JDK,我認爲OP是。 http://stackoverflow.com/questions/7662902/what-is-the-purpose-class-fornamemy-jdbc-driver/7662950#7662950 – maba

1
Add Mysql jar then this code will be connect.