这是下面给出的程序的输出:
Connection made!
Schema Name:null
Successfully connected to null
Releasing all open resources ...
在establishConnection()内,conn被初始化为null.然后try块中的第一个语句应该与数据库建立连接,然后第三个语句打印conn的当前模式的名称.
根据API,getSchema()返回当前模式名称,如果没有则返回null.
这意味着没有与conn关联的模式(我认为模式名称与数据库名称相同)?任何人都可以建议我的预期是否正确,并且还建议为什么没有架构或与conn相关联的null?
public class ConnectDB {
private Connection establishConnection() throws SQLException {
Connection conn = null;
try {
conn = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/test_final1", "root", "password");
System.out.println("Connection made!");
System.out.println("Schema Name:"+conn.getSchema()+"\n");
} catch (SQLException sqle) {
System.err.println("SQL Exception thrown while making connection");
printSQLException(sqle);
}
return conn;
}
public static void main(String[] args) {
ConnectDB cdb= new ConnectDB();
Connection myconn=null;
try{
myconn=cdb.establishConnection();
if(myconn!=null) System.out.println("Successfully connected to " + myconn.getSchema());
}catch (SQLException e) {
ConnectDB.printSQLException(e);
} catch (Exception e) {
e.printStackTrace(System.err);
} finally {
ConnectDB.closeConnection(myconn);
}
}
解决方法:
MySQL不支持模式的概念.对于MySQL,模式实际上是数据库.从MySQL Glossary开始:
schema
Conceptually, a schema is a set of interrelated database objects, such as tables, table columns, data types of the columns, indexes, foreign keys, and so on. (…)
The JDBC driver (because of legacy, mysql didn’t call them “schemas” until 5.0, and JDBC didn’t have a way to select schemas until JDBC4), calls databases “catalogs”, so thus you have to call getCatalogs() to get the list of databases
我做了一个脏的快速证明上面的斜体句子(除非你使用最新的JDBC jar驱动程序).使用getCatalog()使用Java 6:
public class DirtyQuickTest {
private static final String url = "jdbc:mysql://localhost:7841/test";
private static final String user = "lmendozaj";
private static final String password = "s3cr3t"; //I won't show you my password
public static void main(String[] args) throws Exception {
Connection con = null;
try {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection(url, user, password);
//commented since doesn't exists in Java 6
//System.out.println(con.getSchema());
System.out.println(con.getCatalog());
} finally {
con.close();
}
}
}
输出:
test
然后我在Java 8中执行相同的代码,并使用mysql-connector-java-5.1.31-bin.jar(当前最新的MySQL的Java连接器驱动程序)取消注释包含getSchema的语句.这是输出:
null
test
这意味着他们仍然不支持getSchema方法.
有关:
标签:java,mysql,jdbc,database-connection,null
来源: https://codeday.me/bug/20190517/1119906.html