我尝试使用Java 1.8_45,IntelliJ IDEA 15 Ultimate和MySQL Connector / J驱动程序版本5.1.37
通过MySQL数据库连接器连接到MySQL数据库。这是代码(删除敏感信息)
import java.sql.* ;
public class Main {
public static void main (String[] args) {
Connection connect = null;
try {
String url = "jdbc:mysql://my_univ.edu:3306/demo";
Class.forName("com.mysql.jdbc.Driver").newInstance();
connect = DriverManager.getConnection(url, "user", "pass"); // returning null
System.out.println("Database connection established");
} catch(Exception e) { // catch block is never executed
System.err.println(e.getMessage());
e.printStackTrace();
} finally { // finally block is never executed
if(connect != null) {
try {
connect.close();
System.out.println("Database connection terminated");
} catch(Exception e) {
e.printStackTrace();
}
}
}
System.out.println("Foo"); // this line is never executed
}
}
我在connect = DriverManager.getConnection(url, "user", "pass")
上设置了一个断点,好像getConnection
的实现方式如下:
public Connection connect(String url, Properties info) throws SQLException {
Properties parsedProps = this.parseFabricURL(url, info);
if(parsedProps == null) {
return null;
} else {
parsedProps.setProperty("fabricProtocol", "http");
if(Util.isJdbc4()) {
try {
Constructor e = Class.forName("com.mysql.fabric.jdbc.JDBC4FabricMySQLConnectionProxy").getConstructor(new Class[]{Properties.class});
return (Connection)Util.handleNewInstance(e, new Object[]{parsedProps}, (ExceptionInterceptor)null);
} catch (Exception var5) {
throw (SQLException)(new SQLException(var5.getMessage())).initCause(var5);
}
} else {
return new FabricMySQLConnectionProxy(parsedProps);
}
}
}
这是失败的行:Properties parsedProps = this.parseFabricURL(url, info);
Properties parseFabricURL(String url, Properties defaults) throws SQLException {
return !url.startsWith("jdbc:mysql:fabric://") ? null : super.parseURL(url.replaceAll("fabric:", ""), defaults);
}
fabric
是什么或为什么需要它。根据这些教程我不应该有:
connect = DriverManager.getConnection(...)
之后停止执行
connect
设置为null,代码永不退出不确定此代码段发生了什么,感谢任何帮助。此外,这是连接到远程服务器上的MySQL数据库的唯一方法吗?有更好,更简单的方法吗?