我有一段简单的代码,可以使用以下2个对象在java上运行mysql查询:
package dbConn;
import java.sql.*;
public class DBAccess{
private Connection conn;
private Statement st;
DBAccess(String driver, String connString, String user, String password) {
try {
Class.forName(driver);
conn = DriverManager.getConnection(connString, user, password);
st = conn.createStatement();
} catch (ClassNotFoundException e) {
System.out.println("Driver class not found.");
} catch (SQLException e) {
System.out.println("Unable to get connection.");
}
}
public void executeSQL(String stmt) {
try {
st.execute(stmt);
} catch (SQLException e) {
System.out.println("Error executing query.");
}
}
public ResultSet executeSQL(String stmt, boolean returns) {
ResultSet rs = null;
try {
rs = st.executeQuery(stmt);
} catch (SQLException e) {
System.out.println("Error executing query.");
}
return rs;
}
public void setAutocommitFalse() throws SQLException {
conn.setAutoCommit(false);
}
public void setAutocommitTrue() throws SQLException {
conn.setAutoCommit(true);
}
public void commitTransaction() throws SQLException{
conn.commit();
}
public void rollbackTransaction() throws SQLException{
conn.rollback();
}
public void closeConn() {
try {
conn.close();
} catch (SQLException e) {
System.out.println("Error closing connection.");
}
}
}
然后这个:
package dbConn;
import java.io.*;
import java.util.TreeMap;
import java.util.Properties;
public class Connector{
private DBAccess conn = null;
public Connector() {
}
public DBAccess getConector() {
TreeMap param = getParams();
if (conn == null) {
conn = new DBAccess("com.mysql.jdbc.Driver","jdbc:mysql://" + param.get("dbhost") + ":" + param.get("dbport") + "/" + param.get("dbschema") + "?useSSL=false",
param.get("dbuser").toString(),param.get("dbpassword").toString());
}
return conn;
}
private TreeMap getParams() {
TreeMap<String, String> parametros = new TreeMap<>();
Properties prop = new Properties();
try {
InputStream input = new FileInputStream(System.getProperty("user.dir") + "/db.properties");
prop.load(input);
} catch (FileNotFoundException e) {
System.out.println("Properties file not found.");
} catch (IOException e) {
System.out.println("Unable to load input file to properties object.");
}
parametros.put("dbhost",prop.getProperty("dbhost"));
parametros.put("dbport",prop.getProperty("dbport"));
parametros.put("dbschema",prop.getProperty("dbschema"));
parametros.put("dbuser",prop.getProperty("dbuser"));
parametros.put("dbpassword",prop.getProperty("dbpassword"));
return parametros;
}
}
为了运行查询,我只需执行以下操作:
String query = "call get_by_id('" + type.getTableName() + "','" + type.getIdField() + "','" + id + "');";
DBAccess conn = new Connector().getConector();
ResultSet rs = conn.executeSQL(query, true);
然后在rs中循环。这很好。但是,当我查看常规日志时:
每次连接和退出之间的所有操作都需要大约一秒钟的时间。我想缩短时间。有没有办法让我的代码不运行set、show和connector语句?是强制性的吗?我知道一秒钟并不多,但我经常调用这些存储过程,当运行一个应用程序时,如果我需要多次运行这个程序,那么延迟对用户不是很友好。
这和我用的司机有关吗?我可以在连接字符串中添加一些内容来避免这种情况吗?
谢谢!
暂无答案!
目前还没有任何答案,快来回答吧!