我正在使用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連接都保持打開狀態。
謝謝!
就像SingleTone設計模式。 – KSHiTiJ 2013-03-04 08:50:49
仍在建設中... – 2013-03-04 11:36:59
意味着連接?是指每次調用該方法建立新的連接?如果是,那麼給你的代碼。 – KSHiTiJ 2013-03-04 11:52:25