我用 Java 编写了一个运行 MySQL 查询并返回结果的函数。我在这里使用这种方法实现了连接池:http ://www.kodejava.org/how-do-i-create-a-database-connection-pool/ 。该功能正在运行,但连接时间仍然与没有池的情况相同约 190 毫秒。有人可以告诉我我做错了什么吗?
这是我的代码:
public static ArrayList<Map<String,Object>> query(String q) throws Exception {
long start, end;
GenericObjectPool connectionPool = null;
String DRIVER = "com.mysql.jdbc.Driver";
String URL = "jdbc:mysql://localhost/dbname";
String USER = "root";
String PASS = "";
Class.forName(DRIVER).newInstance();
connectionPool = new GenericObjectPool();
connectionPool.setMaxActive(10);
ConnectionFactory cf = new DriverManagerConnectionFactory(URL, USER, PASS);
PoolableConnectionFactory pcf = new PoolableConnectionFactory(cf, connectionPool, null, null, false, true);
DataSource ds = new PoolingDataSource(connectionPool);
//create statement
Statement Stm = null;
try {
Connection Con = null;
PreparedStatement stmt = null;
start = System.currentTimeMillis();
Con = ds.getConnection();
end = System.currentTimeMillis();
System.out.println("DB Connection: " + Long.toString(end - start) + " ms");
//fetch out rows
ArrayList<Map<String, Object>> Rows = new ArrayList<Map<String,Object>>();
Stm = Con.createStatement();
//query
ResultSet Result = null;
boolean Returning_Rows = Stm.execute(q);
if (Returning_Rows) {
Result = Stm.getResultSet();
} else {
return new ArrayList<Map<String,Object>>();
}
//get metadata
ResultSetMetaData Meta = null;
Meta = Result.getMetaData();
//get column names
int Col_Count = Meta.getColumnCount();
ArrayList<String> Cols = new ArrayList<String>();
for (int Index=1; Index<=Col_Count; Index++) {
Cols.add(Meta.getColumnName(Index));
}
while (Result.next()) {
HashMap<String,Object> Row = new HashMap<String,Object>();
for (String Col_Name:Cols) {
Object Val = Result.getObject(Col_Name);
Row.put(Col_Name,Val);
}
Rows.add(Row);
}
//close statement
Stm.close();
//pass back rows
return Rows;
} catch (Exception Ex) {
System.out.print(Ex.getMessage());
return new ArrayList<Map<String,Object>>();
} finally {
if (Stm != null) {
Stm.close();
}
if (Stm != null) {
Stm.close();
}
System.out.println("Max connections: " + connectionPool.getMaxActive());
System.out.println("Active connections: " + connectionPool.getNumActive());
System.out.println("Idle connections: " + connectionPool.getNumIdle());
}
}
每次都是控制台输出:
DB Connection: 186 ms
Max connections: 10
Active connections: 1
Idle connections: 0
更新:我应该注意,使用它的 Java 应用程序是这样工作的:执行,只运行一个查询并关闭。我想如果 PHP 是这样工作的,并且默认情况下它使用连接池,那么 Java 也应该如此吗?如我错了请纠正我。