我正在使用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