-5

I'm learning how to connect to mysql from java from a book, but I get one error, the first line..the package declaration. I copied the code(given bellow) exactly as it was in the book and I have downloaded everything correctly, please help! Thanks!

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();
}
}
Ariful Islam
  • 7,639
  • 7
  • 36
  • 54
user1062436
  • 43
  • 1
  • 2

3 Answers3

1
Add Mysql jar then this code will be connect.
shaji
  • 137
  • 1
  • 3
1

If you have an error on your package declaration, it's probably because you don't have it in the right package!

If you have package mysql; as you state in your code, then you need it to be in the mysql folder in your source tree.

corsiKa
  • 81,495
  • 25
  • 153
  • 204
0

You should write

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

to load the drivers and

connection = DriverManager.getConnection("jdbc:mysql://localhost/accounts","yourUsername","yourPassword");  
gprathour
  • 14,813
  • 5
  • 66
  • 90
  • That's no longer necessary unless you are on a JDK pre-1.6 and I presume the OP is. http://stackoverflow.com/questions/7662902/what-is-the-purpose-class-fornamemy-jdbc-driver/7662950#7662950 – maba Jun 29 '12 at 10:20