如何在Java中保持连接活跃 [英] How to keep connection alive in java

查看:126
本文介绍了如何在Java中保持连接活跃的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用MySQL进行我的第一个Java项目.每当从数据源获取数据时,我都会调用一个函数.此函数应将新行保存到我的MySQL数据库中.在此处查看代码:

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:

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.要调用此函数,我将该类导入另一个类,并使用以下语法:

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:

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.

此功能可以在短时间内快速多次调用.我知道我不必每次调用该函数时都重新打开与MySQL服务器的连接.我将如何更改它,以使每次调用该函数时1个MySQL连接保持打开状态.

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.

谢谢!

推荐答案

您需要管理一个静态类或方法.

you need to manage one static class or method.

喜欢

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方法即可.

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.

所以您只需要遵循我们的代码中的内容即可.

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();
}

这篇关于如何在Java中保持连接活跃的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆