繁体   English   中英

如何在try-catch块中重新连接到数据库?

[英]How to reconnect to database within try-catch block?

我有一个Java应用程序,它使用Spring JDBCTemplate对MySQL数据库执行连续不间断的快速插入。 几分钟后,数据库上显然发生了某些事情,断开了数据库连接,但出现异常

org.springframework.jdbc.CannotGetJdbcConnectionException: Could not get JDBC Connection; nested exception is com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure

我能够在代码中捕获SQLException,因此在这一点上,我想重新建立数据库连接并退出catch块并继续。

有什么方法可以做到这一点?

编辑:这是捕获异常的方法:

public int insertRecord(final String sql,final Object[] paramArray, KeyHolder keyHolder) {

        Integer retStatus = jdbcTemplate.update(new PreparedStatementCreator() { 

            public PreparedStatement createPreparedStatement(Connection con) { 
                    String[] keyColNames=new String[1];
                    PreparedStatement ps = null;
                    try {
                        ps=con.prepareStatement(sql,keyColNames); 
                        if(paramArray!=null){
                            int size=paramArray.length;
                            for(int i=0;i<size;i++){
                                ps.setObject(i+1, paramArray[i]);
                            }
                        }
                    } catch (CannotGetJdbcConnectionException e) {
                        logger.debug("caught SQLexception, now what should I do?");
                        con.reconnectToDatabase();  // this method doesnt exist but is what I need!
                    }

                    return ps; 
                } 
            }, keyHolder);  
        return retStatus;
    }

更新:

如果只希望重新连接数据库,则可以为此专门创建一个类,为其创建一个getConnection方法,然后简单地返回重新建立的连接。 例如:

public class ConnectionManager {

private Connection connection;
public String driverURL = "[Your driver URL]";

    public Connection getConnection(String user, String password) {
    try {
        //SQLServerDriver or whichever you are using
        Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
        connection = DriverManager.getConnection(driverURL, username, password);
    }catch(ClassNotFoundException e) {
        e.printStackTrace();
    }
    catch(SQLException e) {
        e.printStackTrace();
    }
    return connection;
}

接着:

con = new ConnectionManager().getConnection(user, pass);

您可以从那里再次调用该方法,然后重试插入或继续进行。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM