在我的代码中,我的最终输出与 MySQl 控制台输出不同:
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() {
String sqlString1 = "use mydb";
String sqlString2 = "show tables";
String result;
try {
Statement st1 = con.createStatement();
ResultSet result1 = st1.executeQuery(sqlString1);
while(result1.next()){
result = result1.getString(dbName);
System.out.println(result1);
}
} catch (SQLException sqle) {
System.out.println("Can not excute sql statement");
}
}
public static void main(String[] args) {
d3 ddd = new d3();
ddd.connectToDB();
ddd.excuteSQL();
}
}
我的输出:
Find database successfuly
Connect to database succesfully
Result set representing update count of 0
但是,我想成为这样的:
Find database successfuly
Connect to database succesfully
Database changed // this is shown in console
我将一步一步比较 mysql 控制台和 IDE 控制台的输出, 例如,我想在执行“use mydb”语句后看到“数据库已更改”消息。
最佳答案
您正在执行use mydb
,它不会生成结果集(它不是查询)。另外,您不应该使用此命令来设置当前数据库,JDBC 要求您使用 JDBC 方法。请参阅java.sql.Connection的javadoc:
Note: When configuring a
Connection
, JDBC applications should use the appropriateConnection
method such assetAutoCommit
orsetTransactionIsolation
. Applications should not invoke SQL commands directly to change the connection's configuration when there is a JDBC method available.
相当于 USE mydb
的是 Connection.setCatalog("mydb")
,调用此方法可确保驱动程序处于一致状态。如果您查看 MySQL Connector/J 中的实际实现,此方法最终会调用 USE mydb,但它还会对 Connection 对象的状态进行额外的检查和更改。
当您已经知道要使用哪个数据库时,只需将其直接包含到连接 URL 中即可:
String dbUrl = "jdbc:mysql://localhost/mydb";
同样,您不应该使用 SHOW TABLES
来获取有关表的信息,请使用 DatabaseMetaData.getTables()
反而。在 MySQL 特定命令上使用 JDBC 方法可以使您的程序更加可移植。
关于java - JDBC MySQl 不显示结果集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17239911/