2013-03-04 166 views
0

我正在使用MySQL開發我的第一個Java項目。每次從數據源獲取數據時,都會調用一個函數。這個函數應該保存一個新行到我的MySQL數據庫。看到這裏的代碼:如何在java中保持連接活着

import java.sql.*; 
import java.util.Properties; 

/** 
* 
* @author jeffery 
*/ 
public class SaveToMysql { 
    // The JDBC Connector Class. 
    private static final String dbClassName = "com.mysql.jdbc.Driver"; 

    private static final String CONNECTION = "jdbc:mysql://localhost/test"; 

    static public String test(int reqId, String date, double open, double high, double low, 
             double close, int volume, int count, double WAP, boolean hasGaps){ 

     if (date.contains("finished")){ 
      return "finished"; 
     } 


     // Class.forName(xxx) loads the jdbc classes and 
     // creates a drivermanager class factory 
     try{ 
      Class.forName(dbClassName); 
     }catch (ClassNotFoundException e) { 
      System.out.println(e); 
     } 

     // Properties for user and password. Here the user and password are both 'paulr' 
     Properties p = new Properties(); 
     p.put("user","XXXXXXXX"); 
     p.put("password","XXXXXXXXXXXx"); 

     // Now try to connect 
     Connection conn; 
     try{ 
      conn = DriverManager.getConnection(CONNECTION,p); 
     }catch(SQLException e){ 
      return e.toString(); 
     } 

     PreparedStatement stmt; 
     try{ 
      stmt = conn.prepareStatement("insert into dj_minute_data set symbol = (select ticker from dow_jones_constituents where id = ?), " 
        + "date = str_to_date(?,'%Y%m%d %H:%i:%s')" + 
      ", open = ?" + 
      ", high = ?" + 
      ", low = ?" + 
      ", close = ?" + 
      ", volume = ?" + 
      ", adj_close = ?"); 
      stmt.setInt(1, reqId); 
      stmt.setString(2, date); 
      stmt.setDouble(3, open); 
      stmt.setDouble(4, high); 
      stmt.setDouble(5, low); 
      stmt.setDouble(6, close); 
      stmt.setDouble(7, volume); 
      stmt.setDouble(8, WAP); 
     }catch (SQLException e){ 
      return e.toString(); 
     } 

     try{ 
      stmt.executeUpdate(); 
     }catch (SQLException e){ 
      return e.toString(); 
     } 

     return stmt.toString(); 
    } 

} 

大家都可以看到這個功能test是在自己的班級,稱爲SaveToMysql。要調用此函數,我將該類導入到不同的類中,並使用以下語法:

msg = SaveToMysql.test(reqId, date, open, high, low, close, volume, count, WAP, hasGaps); 

msg然後獲取輸出到屏幕。顯示錯誤消息或成功。

該功能可以在短時間內快速調用多次。我知道每次調用函數時都不應該重新打開與MySQL服務器的連接。我將如何改變這一點,以便每次調用該函數時,MySQL連接都保持打開狀態。

謝謝!

回答

1

您需要管理一個靜態類或方法。

public class ConnectionClass 
{ 
    public static Connection connection = null; 

    public Connection getCurrentConnection() 
    { 
     if(connection != null) 
     { 
      return connection; 
     } 
     else 
     { 
      create new connection... 
        and return that new connection after giving it to global connection.. 
     } 
    } 
} 
每次

這個你會得到當前連接。如果有問題並且連接不可用,則可以創建新的連接。當你需要連接對象時,你只需要調用getCurrentConnection方法。

所以你只需要在你的代碼中進行以下操作。

Connection conn; 
try{ 
    //conn = DriverManager.getConnection(CONNECTION,p); 
     conn = getCurrentConnection(); 
}catch(SQLException e){ 
    return e.toString(); 
} 
+0

就像SingleTone設計模式。 – KSHiTiJ 2013-03-04 08:50:49

+0

仍在建設中... – 2013-03-04 11:36:59

+0

意味着連接?是指每次調用該方法建立新的連接?如果是,那麼給你的代碼。 – KSHiTiJ 2013-03-04 11:52:25

2

我知道我不應該在每次調用函數時重新打開與MySQL服務器的連接。

不,它的罰款這樣做 - 只要你有在引擎蓋下的連接池管理真正連接。有各種連接池項目,如c3p0DBCP。這樣,你可以讓您的每一個電話從相互隔離的:

  • 取從池中的連接
  • 使用它
  • 其釋放回池中

見文檔無論您選擇哪個泳池作爲細節。通常,連接池允許您像往常一樣從JDBC請求連接,然後按正常方式關閉它,從而有效地使整個事情變得透明。

另請注意,您應該肯定開始使用帶有參數的預準備語句,而不是直接在您的SQL語句中包含您的值。您當前的代碼是等待發生的SQL injection attack

+0

感謝擡頭有關安全,我會更新我的問題,以便不給別人如何做這個錯誤的想法。 – 2013-03-04 08:01:24

0

如果你想使用1個連接時調用SaveToMysql.test方法很多次,你可以添加方法參數的連接,或創建一個全局變量連接出方SaveToMysql.test方法。但是,如果您使用1個連接,請注意事務。我希望它能幫助你。

2

JDBC URL:jdbc:mysql://:/? connectTimeout = 0 &了socketTimeout = 0 & autoReconnect的=真