我在网络服务中遇到了MySQL连接..
public class DBAccessLayer
{
private Connection connection = null;
private Statement statement = null;
private String DBFormatter = "'";
private String key;
private static DataSource datasource = null;
private static boolean _isInitiated = false;
private static boolean _isInitializing = false;
public DBAccessLayer()
{
key = ConstantValues.getKey();
SetPoolSettings();
}
private void SetPoolSettings()
{
try
{
if (!_isInitiated && !_isInitializing)
{
_isInitializing = true;
PoolProperties p = new PoolProperties();
p.setUrl("jdbc:mysql://localhost:3306/DBName?autoReconnect=true");
p.setDriverClassName("com.mysql.jdbc.Driver");
p.setUsername("root");
p.setPassword("password");
p.setJmxEnabled(true);
p.setTestWhileIdle(false);
p.setTestOnBorrow(true);
p.setValidationQuery("SELECT 1");
p.setTestOnReturn(false);
p.setValidationInterval(30000);
p.setTimeBetweenEvictionRunsMillis(30000);
p.setMaxActive(100);
p.setInitialSize(10);
p.setMaxWait(10000);
p.setRemoveAbandonedTimeout(60);
p.setMinEvictableIdleTimeMillis(30000);
p.setMinIdle(10);
p.setLogAbandoned(true);
p.setRemoveAbandoned(true);
p.setFairQueue(true);
p
.setJdbcInterceptors("org.apache.tomcat.jdbc.pool.interceptor.ConnectionState;org.apache.tomcat.jdbc.pool.interceptor.StatementFinalizer");
datasource = new DataSource();
datasource.setPoolProperties(p);
_isInitiated = true;
}
}
finally
{
_isInitializing = false;
}
}
public void OpenConnection() throws SQLException
{
if (connection == null || connection.isClosed())
connection = datasource.getConnection();
if (statement == null || statement.isClosed())
statement = connection.createStatement();
}
public Statement getStatement() throws Exception
{
if (connection == null || connection.isClosed())
connection = datasource.getConnection();
statement = connection.createStatement();
return statement;
}
public void CloseConnection()
{
try
{
if (statement != null)
statement.close();
}
catch (Exception ignore)
{
ignore.printStackTrace();
}
try
{
if (connection != null)
connection.close();
}
catch (Exception ignore)
{
ignore.printStackTrace();
}
}
}
这是我用来连接Web服务中的数据库的类。我有一些使用相同Web服务运行的石英预定作业。
我在每个Web服务方法调用上调用OpenConnection()方法,并在每个作业开始时调用,最后调用CloseConnection()。
但我经常收到这个错误,而我在try - finally阻止只关闭一次连接。
com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException:语句关闭后不允许任何操作。
所以我的网络服务方法看起来像
private DBAccessLayer _DBAccessLayer = null;
private DBAccessLayer getDBAccessLayer()
{
if (_DBAccessLayer == null)
_DBAccessLayer = new DBAccessLayer();
rerurn _DBAccessLayer;
}
public void dummyCall()
{
try
{
getDBAccessLayer.getStatement().executeQuery("Some query");
}
finally
{
getDBAccessLayer.CloseConnection();
}
}