我正在使用 MySQL 开发我的第一个 Java 项目。我有一个函数,每次从数据源取回数据时都会调用该函数。此函数应将新行保存到我的 MySQL 数据库中。请参阅此处的代码:
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);
消息然后输出到屏幕。显示错误消息或成功。
该函数可能会在短时间内被快速调用多次。我知道我不应该在每次调用该函数时都重新打开与 MySQL 服务器的连接。我该如何更改它,以便 1 个 MySQL 连接在每次调用该函数时保持打开状态。
谢谢!!
最佳答案
JDBC 网址:jdbc:mysql://:/? connectTimeout=0&socketTimeout=0&autoReconnect=true
关于java - 如何在java中保持连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15196739/