2011-11-23 56 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.