我的错误在哪里?
我在课堂上运行此方法,但确实发生了异常。为什么?
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)