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

时间:2014-04-25 21:16:52

标签: java mysql jdbc null database-connection

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

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

    }

1 个答案:

答案 0 :(得分:6)

MySQL不支持架构的概念。对于MySQL,模式实际上是数据库。来自MySQL Glossary

  

<强>模式

     

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

基于this answer from MySQL forums,您无法通过Connection#getSchema方法(自Java 7与JDBC 4一起添加)获取当前数据库(或数据库),但使用Connection#getCatalog 除非您使用最新的JDBC jar驱动程序

  

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

输出:

test

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

null
test

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

相关: