java 如何在java中保持连接活跃
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15196739/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to keep connection alive in java
提问by jeffery_the_wind
I am working on my first Java Project with MySQL. I have one function that gets called every time I get data back from my data source. This function should save a new line to my MySQL database. See the code here:
我正在使用 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();
}
}
As you all can see this function test
is in its own class, called SaveToMysql
. To call this function, I import the class into a different class, and use this syntax:
正如你们所看到的,这个函数test
在它自己的类中,称为SaveToMysql
. 为了调用这个函数,我将该类导入到另一个类中,并使用以下语法:
msg = SaveToMysql.test(reqId, date, open, high, low, close, volume, count, WAP, hasGaps);
The msg then get output to the screen. Showing either error message or success.
然后 msg 将输出输出到屏幕上。显示错误消息或成功。
This function may be called many times rapidly in a short time period. I know I should not have to re-open my connection with the MySQL server every time the function gets called. How would I change this so that the 1 MySQL connection stays open for every call to the function.
该函数可能会在短时间内被快速调用多次。我知道每次调用该函数时我都不必重新打开与 MySQL 服务器的连接。我将如何更改这一点,以便每次调用该函数时 1 个 MySQL 连接都保持打开状态。
Thanks!!
谢谢!!
回答by devdanke
JDBC URL: jdbc:mysql://:/? connectTimeout=0&socketTimeout=0&autoReconnect=true
JDBC URL:jdbc:mysql://:/? connectTimeout=0&socketTimeout=0& autoReconnect=true
回答by Jon Skeet
I know I should not have to re-open my connection with the MySQL server every time the function gets called.
我知道每次调用该函数时我都不必重新打开与 MySQL 服务器的连接。
No, it's fine to do so - as long as you have a connection pool under the hood to manage the realconnections. There are various connection pool projects around, such as c3p0and DBCP. That way you can make each of your calls isolated from the others:
不,这样做很好 - 只要您在后台有一个连接池来管理真正的连接。周围有各种连接池项目,例如c3p0和DBCP。这样您就可以将您的每个调用与其他调用隔离开来:
- Fetch a connection from the pool
- Use it
- Release it back to the pool
- 从池中获取连接
- 用它
- 将其释放回池中
See the documentation for whichever pool you choose for the details. Often connection pools allow you to just request a connection from JDBC as normal and then close it as normal, effectively making the whole thing transparent.
有关详细信息,请参阅您选择的任何池的文档。通常,连接池允许您像往常一样从 JDBC 请求连接,然后像往常一样关闭它,从而有效地使整个事情变得透明。
Also note that you should definitelystart using prepared statements with parameters rather than including your values directly in your SQL statement. Your current code is a SQL injection attackwaiting to happen.
另请注意,您绝对应该开始使用带参数的准备好的语句,而不是直接在 SQL 语句中包含您的值。您当前的代码是等待发生的SQL 注入攻击。
回答by KSHiTiJ
you need to manage one static class or method.
您需要管理一个静态类或方法。
like
喜欢
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..
}
}
}
by this every time you will get current connection. and if there is some issue and connection is not available then you can create new connection. when you need connection object you just need to call getCurrentConnection method.
每次你都会得到当前的连接。如果出现问题并且连接不可用,那么您可以创建新连接。当您需要连接对象时,您只需要调用 getCurrentConnection 方法。
so you just need to following things in ur code.
所以你只需要遵循你的代码中的内容。
Connection conn;
try{
//conn = DriverManager.getConnection(CONNECTION,p);
conn = getCurrentConnection();
}catch(SQLException e){
return e.toString();
}
回答by n2h
If you want use 1 connection when call SaveToMysql.test method many times, you can add your connection in method parameter, or create a global connection variable out side SaveToMysql.test method. but, if you use 1 connection, please attention about transaction. I hope it will help you.
如果您想在多次调用 SaveToMysql.test 方法时使用 1 个连接,您可以在方法参数中添加您的连接,或者在 SaveToMysql.test 方法之外创建一个全局连接变量。但是,如果您使用 1 个连接,请注意交易。我希望它会帮助你。