0

私の間違いはどこですか?

クラスでこのメソッドを実行しましたが、例外が発生しました。なんで?

public class d3 {

Connection con;
String dbName = "mydb";
String dbUsername = "root";
String dbPassword = "2323";
String dbUrl = "jdbc:mysql://localhost/";

public d3() {
    try {
        Class.forName("com.mysql.jdbc.Driver");
        System.out.println("Find database successfuly");
    } catch (Exception e) {
        System.err.println("Unable to find and load driver");
        System.exit(1);
    }
}

public void connectToDB() {
    try {
        con = DriverManager.getConnection(dbUrl, dbUsername, dbPassword);
        System.out.println("Connect to database succesfully");
    } catch (SQLException e) {
        System.out.println("Can not connect to database");
        System.exit(1);
    }
}

public void excuteSQL() {
    try {
        Statement st1 = con.createStatement();
        ResultSet result1 = st1.executeQuery("select * from mytable");
        while(result1.next()){
            System.out.println(result1);
        }

    } catch (SQLException sqle) {
        System.out.println("Can not excute sql statement");
        sqle.printStackTrace();
    }
}

public static void main(String[] args) {
    d3 ddd = new d3();
    ddd.connectToDB();
    ddd.excuteSQL();
}
}

出力:

Can not excute sql statement

スタックトレース:

java.sql.SQLException: No database selected
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1073)
    at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3609)
    at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3541)
    at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2002)
    at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2163)
    at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2618)
    at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2568)
    at com.mysql.jdbc.StatementImpl.executeQuery(StatementImpl.java:1557)
    at JDBCtest.d3.excuteSQL(d3.java:40)
    at JDBCtest.d3.main(d3.java:54)
4

4 に答える 4

1

URLにデータベース名を指定する必要があります

String dbUrl = "jdbc:mysql://localhost/mydb";

または、各SQLクエリでテーブル名を完全に修飾できます

ResultSet result1 = st1.executeQuery("select * from mydb.mytable");
于 2013-06-24T11:37:04.023 に答える
1

dbUrl 変数は次のようになります。

 String dbUrl = "jdbc:mysql://localhost:3306/mydb";
于 2013-06-24T11:38:11.993 に答える
1

SQLConnection に問題があるようです ... 接続が正常に確立されていることを確認してください。

データベースを選択していません。

于 2013-06-24T11:29:08.117 に答える