如何使SQL连接语句通用

我必须在同一个类的不同方法中执行几个SQL查询。 有没有办法使这些语句通用,我可以在所有方法中使用相同的con,语句变量来执行查询。

Class.forName("com.mysql.jdbc.Driver").newInstance(); Connection con = DriverManager.getConnection ("jdbc:mysql://localhost:3306/kamal","root","root"); Statement statement=con.createStatement(); 

在您的class级中使用此方法并一次又一次地调用它

 public Connection getMyConnection() throws ClassNotFoundException, SQLException { String connectionURL = "jdbc:mysql://localhost:3306/test"; Class.forName("com.mysql.jdbc.Driver"); Connection con = DriverManager.getConnection(connectionURL, "root", "root"); return con; } 

您可以使用静态方法编写连接语句,该方法可以在其他类中重复使用:

 public Connection getConnection() throws ClassNotFoundException, SQLException { String connURL = "jdbc:mysql://localhost:3306/test"; Class.forName("com.mysql.jdbc.Driver"); Connection con = DriverManager.getConnection(connURL, "username", "password"); return con; } 

但是这有一个缺点,你必须手动管理数据库连接的打开和关闭。

为了缓解上述缺点,请考虑使用像Hibernate这样的对象关系映射框架,它将连接细节抽象为将重新用于每个数据库连接的设置文件。

如果您需要整个类中的变量,您可能希望将其变为成员变量。

但是,对于像Connections这样的资源,这是不受欢迎的,因为它很容易剥夺系统,并增加额外的负载。

你可以做的是使用一个名为Singleton的设计模式。 在这里阅读它。

基本上,您可以使用此实现创建一个名为ConnectionManager的新类

 class ConnectionManager { private static ConnectionManager _instance = null; private Connection con = null; protected ConnectionManager() { //empty } private void init() { Class.forName("com.mysql.jdbc.Driver").newInstance(); this.con = DriverManager.getConnection ("jdbc:mysql://localhost:3306/kamal","root","root"); } public Connection getConnection() { return this.con; } public static ConnectionManager getInstance() { if(_instance == null) { _instance = new ConnectionManager(); _instance.init(); } return _instance; } }//end class 

现在,这可以通过多种方式帮助我们,特别是如果您的应用程序是multithreading的。 我们只需要建立一个连接,除非程序已被终止,否则它将保持不变。 你需要创建一个新的Statement ,你可以简单地使用它。

 ConnectionManager.getInstance().getConnection().createStatement(); 

这是一个非常天真的连接池实现。 请注意,这是使用记事本编写的,尚未经过测试:

 public interface ConnectionPool { public Connection getConnection() throws SQLException; public void closeConnection(Connection connection) throws SQLException; } public class MySQLConnectionPool implements ConnectionPool { private static final Class mysqlDriver; private final Stack connections; private final String url; private final String user; private final String password; private final int maxSize; static { mysqlDriver = Class.forName("com.mysql.jdbc.Driver"); } public MySQLConnectionPool(String url, String user, String password, int initialSize, int size) { if (initialSize > size) { throw new IllegalArgumentException("Pool initial size must not be greater than size"); } if (size <= 0) { throw new IllegalArgumentException("Pool size must be greater than zero"); } this.size = maxSize; this.url = url; this.user = user; this.password = password; this.connections = new Stack(); try { for (int i = 0;i < initialSize;i++) { connections.push(getConnection(url, user, password)); } } catch (Exception exception) { // TODO: Log somewhere? } } public Connection getConnection(String url, user, password) throws SQLException { DriverManager.getConnection(url, user, password); } public Connection getConnection() SQLException { try { synchronized (connections) { return connections.pop(); } } catch (EmptyStackException exception) { return getConnection(url, user, password); } } public void closeConnection(Connection connection) throws SQLException { synchronized (connections) { if (connections.size() < maxSize) { connections.push(connection); return; } } connection.close(); } } public class SingletonMYSQLConnectionPool extends MySQLConnectionPool() { private static volatile SingletonMYSQLConnectionPool instance; private SingletonMYSQLConnectionPool() { super("jdbc:mysql://localhost:3306/kamal","root","root", 0, 2); } public static SingletonMYSQLConnectionPool getInstance() { if (instance == null) { synchronized (SingletonMYSQLConnectionPool.class) { if (instance == null) { instance = new SingletonMYSQLConnectionPool(); } } } return instance; } } 
 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { PrintWriter pw = response.getWriter(); Connection conn; try { String fname = request.getParameter("fname"); String lname = request.getParameter("lname"); Class.forName("com.mysql.jdbc.Driver"); conn = (Connection)DriverManager.getConnection("jdbc:mysql://localhost:3307/soft\",\"root\",\"root"); PreparedStatement pst = (PreparedStatement) conn.prepareStatement("insert into soft.IT(fname,lname) values(?,?)"); pst.setString(1,fname); pst.setString(2,lname); int i = pst.executeUpdate(); if(i!=0){ pw.println("
Record has been inserted"); } else { pw.println("failed to insert the data"); } }catch (Exception e) { pw.println(e); } }

将它们存储在数据库中。