我正在尝试在我的 Java 应用程序中使用 HikariCP JDBC 连接池。我的应用程序中没有使用 Spring 或 Hibernate 等任何框架。目前,我可以使用简单的 JDBC 驱动程序连接到 MySQL DB,但是当我尝试使用 Hiraki 时,代码无法正常工作。即使初始化数据源后也不明白我哪里出了问题。
初始 JDBC 工作代码..
public class Connect extends ErrorCat{
protected Connection connection = null;
//Database user name and password
private String name = "root";
private String pass = "";
//Database URL and JDBC Driver
private String url = "jdbc:mysql://127.0.0.1:3306/fls";
private String driver = "com.mysql.jdbc.Driver";
protected /*static Connection*/void getConnection(){
if (connection == null){
System.out.println("Registering driver....");
try {
//Driver Registration
Class.forName(driver).newInstance();
System.out.println("Driver Registered successfully!!.");
//Initiate a connection
System.out.println("Connecting to database...");
connection = DriverManager.getConnection(url, name, pass);
System.out.println("Connected to database!!!");
} catch (InstantiationException | IllegalAccessException | ClassNotFoundException e) {
e.printStackTrace();
System.out.println("Couldnt register driver...");
} catch (SQLException e) {
e.printStackTrace();
System.out.println("Couldnt connect to database...");
}
}
//return connection;
}
}
更新了代码(不起作用)..
public class Connect extends ErrorCat{
protected Connection connection = null;
protected Connection connection = null;
protected HikariDataSource ds = null;
protected static Connection instance = null;
protected /*static Connection*/void getConnection() {
if (connection == null){
System.out.println("Registering driver....");
Connect ct = new Connect();
ct.HikariGFXDPool();
}
//return connection;
}
protected void HikariGFXDPool(){
HikariConfig config = new HikariConfig();
config.setJdbcUrl("jdbc:mysql://localhost:3306/simpsons");
config.setUsername("bart");
config.setPassword("51mp50n");
config.addDataSourceProperty("cachePrepStmts", "true");
config.addDataSourceProperty("prepStmtCacheSize", "250");
config.addDataSourceProperty("prepStmtCacheSqlLimit", "2048");
HikariDataSource ds = new HikariDataSource(config);
}
}
我认为真正的问题是,在 HikariGFXDPool 方法中,您创建了一个局部变量和类变量 protected HikariDataSource ds = null;保持为空。 所以你无法连接。
最好的方法是使用单独的类来建立和获取连接,如下所示:
public class DBHandler{
private static HikariDataSource ds;
static{
HikariConfig config = new HikariConfig();
config.setJdbcUrl("jdbc:mysql://localhost:3306/simpsons");
config.setUsername("bart");
config.setPassword("51mp50n");
config.setDriverClassName("com.mysql.jdbc.Driver");
config.addDataSourceProperty("cachePrepStmts", "true");
config.addDataSourceProperty("prepStmtCacheSize", "250");
config.addDataSourceProperty("prepStmtCacheSqlLimit", "2048");
ds = new HikariDataSource(config);
}
public static Connection getConn() throws SQLException {
return ds.getConnection();
}
}
然后,在您的其他课程中,您可以使用以下方式获得连接:
Connection conn = DBHandler.getConn();
// query
conn.close();