我编写了一个Java类,用于在我的程序中运行MS Sql查询。这个程序为每个应该运行的查询建立一个新的连接。我知道这会增加我的延迟。这里是CALSS代码:使用JDBC运行的查询
import java.sql.*;
public abstract class DatabaseManager {
public static ResultSet executeQuery(String SQL, String dbName)
{
ResultSet rset = null ;
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
String connectionUrl = "jdbc:sqlserver://localhost:1433;" +
"databaseName="+dbName+";user=??;password=??;";
Connection con = DriverManager.getConnection(connectionUrl);
Statement st = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_READ_ONLY);
rset = st.executeQuery(SQL);
//st.close();
}
catch (ClassNotFoundException e) {}
catch (SQLException e) {}
return rset;
}
public static void executeUpdate(String SQL, String dbName)
{
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
String connectionUrl = "jdbc:sqlserver://localhost:1433;" +
"databaseName="+dbName+";user=??;password=??;";
Connection con = DriverManager.getConnection(connectionUrl);
Statement st = con.createStatement();
st.executeUpdate(SQL);
st.close();
con.close();
}
catch (ClassNotFoundException e) {System.out.println(e);}
catch (SQLException e) {System.out.println(e);}
}
}
我怎么能在仅创建了一个连接和throught是连接我所有的查询路线的方式改变? 此致敬礼。
使用Singleton模式 – SpringLearner
使连接在你的班上一个单身?真的,你应该考虑一些可以提供借鉴和其他整洁的东西的集合选项(如C3PO)。 –
这可能对你有所帮助http://rdeshapriya.com/a-singleton-java-class-for-mysql-db-connection/ – SpringLearner