java jdbc getschema_java – JDBC:连接返回NULL,该怎么办?

这是下面给出的程序的输出:

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值