JDBC:连接返回NULL,该怎么办?

Sol*_*ace 5 java mysql null database-connection jdbc

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

Connection made!
Schema Name:null

Successfully connected to null
Releasing all open resources ...
Run Code Online (Sandbox Code Playgroud)

在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);
        }

    }
Run Code Online (Sandbox Code Playgroud)

Lui*_*oza 6

MySQL不支持模式的概念.对于MySQL,模式实际上是数据库.来自MySQL词汇表:

模式

从概念上讲,模式是一组相互关联的数据库对象,例如表,表列,列的数据类型,索引,外键等.(......)

根据MySQL论坛的答案,您无法通过Connection#getSchema方法(自Java 7与JDBC 4一起添加)获取当前数据库(或数据库),但除非您使用最新的JDBC jar驱动程序,否则使用它:Connection#getCatalog

JDBC驱动程序(因为遗留问题,mysql在5.0之前没有将它们称为"模式",而JDBC在JDBC4之前没有办法选择模式),调用数据库"目录",因此你必须调用getCatalogs()获取数据库列表

我做了一个脏的快速证明上面的斜体句子(除非你使用最新的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();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

输出:

test
Run Code Online (Sandbox Code Playgroud)

然后我在Java 8中执行相同的代码并取消注释包含getSchemamysql-connector-java-5.1.31-bin.jar 的语句(目前是MySQL的最新Java连接器驱动程序).这是输出:

null
test
Run Code Online (Sandbox Code Playgroud)

这意味着他们仍然不支持getSchema方法.

有关: