我有一个使用MySQL和HikariCP进行连接池的Web应用程序。我使用像这样定义的单例连接池对象连接到我的池:
package com.webapp.db;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import javax.sql.DataSource;
import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
import org.apache.log4j.Logger;
public class HikariConnectionPool
{
private static final Logger log = Logger.getLogger(HikariConnectionPool.class.getName());
private static volatile HikariConnectionPool hikariCP = null;
private static HikariDataSource hikariDataSource = null;
private HikariConnectionPool() // We don't want any other object creating this pool
{
HikariConfig config = new HikariConfig();
config.addDataSourceProperty("url","jdbc:mysql://remoteMYSQLServer:3306/webapp");
config.addDataSourceProperty("user", "webapp");
config.addDataSourceProperty("password", "password");
config.setMinimumIdle(1);
config.setMaximumPoolSize(2);
config.setInitializationFailFast(true);
config.setConnectionTestQuery("VALUES 1");
config.setJdbcUrl("jdbc:mysql://remoteMYSQLServer:3306/webapp");
config.setDriverClassName ("com.mysql.jdbc.Driver");
hikariDataSource = new HikariDataSource (config);
}
public static HikariConnectionPool getInstance()
{
if (hikariCP == null)
{
synchronized (HikariConnectionPool.class)
{
if (hikariCP == null)
{
hikariCP = new HikariConnectionPool ();
}
}
}
return hikariCP;
}
public static HikariDataSource getDataSource ()
{
hikariCP = getInstance ();
return hikariDataSource;
}
}
在我的应用程序中,我使用以下代码来获取数据源:
HikariDataSource ds = HikariConnectionPool.getDataSource ();
然后尝试使用
插入数据库try {
Connection connection = ds.getConnection ();
String sString = "insert into webapp.sometable (?, ?, ?, ?, ?);";
PreparedStatement statement = connection.prepareStatement (sString);
statement.setString (1, fname);
statement.setString (2, sname);
statement.setString (3, email);
statement.setString (4, password);
statement.setString (5, phone);
statement.executeUpdate();
connection.commit ();
connection.close ();
} catch (SQLException e) { e.printStackTrace(); }
但我没有看到提交给数据库的值。我究竟做错了什么?非常感谢任何帮助。
答案 0 :(得分:6)
带有双重检查锁定的getInstance()不正确,可能导致竞争条件。有关正确的模式,请参阅"Double-checked locking" on Wikipedia。
您的SQL语句不需要以分号结尾。它可能不需要使用模式“webapp”进行限定。因为您明确连接到webapp数据库。
另外,我会跳过构建数据源的Driver Manager版本,并采用以下模式:
HikariConfig config = new HikariConfig();
config.setMinimumIdle(1);
config.setMaximumPoolSize(2);
config.setInitializationFailFast(true);
config.setConnectionTestQuery("VALUES 1");
config.setDataSourceClassName("com.mysql.jdbc.jdbc2.optional.MysqlDataSource");
config.addDataSourceProperty("serverName", "localhost");
config.addDataSourceProperty("port", "3306");
config.addDataSourceProperty("databaseName", "webapp");
config.addDataSourceProperty("user", "webapp");
config.addDataSourceProperty("password", "password");