共同

2013-02-16 22 views
3

如何使SQL語句連接我在同一類的不同的方法來執行多個SQL查詢。有什麼辦法可以使這些語句變得很常見,並且我可以在所有方法中使用相同的con,statement變量來執行查詢。共同

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

什麼是你想實現什麼? – 2013-02-16 20:25:11

回答

3

你可以編寫連接語句在靜態方法,在你的其他類可以重複使用:

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對象關係映射框架,這將抽象的連接細節將被重新用於每個數據庫連接的設置文件。

+0

沒有理由讓方法變爲靜態。 – 2013-02-16 20:24:49

+0

對,我會編輯出來的。 – 2013-02-16 20:26:57

+0

沒有理由使該方法非靜態。 – Abdull 2016-04-14 11:21:12

1

如果您需要在整個類的變量,你可能要使它成爲一個成員變量。

然而,這是鼓勵使用資源,如Connections,因爲它可以很容易地剝奪一個系統,以及把額外的負擔。

你可以做的是使用名爲Singleton的設計模式。閱讀關於它here

基本上,你可以創建一個名爲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 

現在,這幫助我們在許多方面,特別是如果你的應用程序是多線程的。我們只需要建立一個連接,除非程序被終止,否則這個連接將保留。無論您需要創建新的Statement,您都可以簡單地使用它。

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

我個人認爲使用連接作爲單例是一個非常糟糕的主意。在多線程環境中,不保證線程安全。連接池可能是正確的選擇。 – 2013-02-16 20:39:28

+0

正確創建的單例非常安全。連接池對於非常大的應用程序來說非常棒,但對於較小的應用程序來說非常麻煩。 – Achrome 2013-02-16 20:42:26

+0

您不應該在多個線程之間共享單個連接。你可以在這裏找到關於線程安全的討論:http://stackoverflow.com/questions/1531073/is-java-sql-connection-thread-safe – 2013-02-16 20:46:12

5

使用這種方法,在你的類,然後再次調用它,並再次

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; 
    } 
-1

讓他們在你的數據庫的存儲過程。

1

這裏是一個非常幼稚的連接池實現。請注意,這是使用記事本編寫的,它沒有經過測試:

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<Connection> 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<Connection>(); 
     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; 
    } 
} 
+0

什麼是重用語句,這是你需要在應用程序級別處理的東西(除非你的容器爲他們提供了緩存 - 但是你會使用數據源) – 2013-02-16 21:19:39

0
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("<br>Record has been inserted"); 
      } 
      else 
      { 
        pw.println("failed to insert the data"); 
      } 
      }catch (Exception e) 
      { 
        pw.println(e); 
      } 
     } 
+0

你使用conn.commit()並關閉連接嗎? – Assafs 2017-09-12 16:51:01