【问题标题】:java mysql quickjava mysql 快速
【发布时间】:2012-01-05 00:05:45
【问题描述】:

我正在从一本书中学习如何从 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();
}
}

【问题讨论】:

  • 这个错误是什么?详情?

标签: java mysql


【解决方案1】:

如果您的包声明有错误,可能是因为您没有将它放在正确的包中!

如果您在代码中声明有package mysql;,那么您需要它位于源代码树的mysql 文件夹中。

【讨论】:

  • 我确实把它放在了正确的包里..谢谢我想通了
【解决方案2】:

你应该写

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

加载驱动程序和

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

【讨论】:

【解决方案3】:
Add Mysql jar then this code will be connect.

【讨论】:

    猜你喜欢
    • 2016-04-21
    • 1970-01-01
    • 2020-09-07
    • 2011-07-01
    • 2015-12-14
    • 2014-10-29
    • 2017-07-28
    • 2012-07-22
    • 1970-01-01
    相关资源
    最近更新 更多