连接到SqlServer没有关闭for循环java

时间:2017-04-17 18:34:26

标签: java sql-server c3p0 jtds

我不确定最佳做法,但我的整体问题是我无法弄清楚为什么我的连接没有关闭。

我基本上遍历列表,然后将它们插入表中。在我将它们插入表格之前,我检查并确保它不是重复的。如果是,我更新行而不是插入它。截至目前,我只能在调试之前让13个迭代工作,让我知道我的连接没有关闭。

由于我有2个连接,因此我无法弄清楚我想要关闭连接的位置,而我正试图使用​​其他示例来提供帮助。这是我得到的:

        Connection con = null;
    PreparedStatement stmt = null;
    PreparedStatement stmt2 = null;
    ResultSet rs = null;
    Connection con2 = null;


    for (Object itemId: aList.getItemIds()){
        try {
            con = cpds2.getConnection();
                stmt = con.prepareStatement("select [ID] from [DB].[dbo].[Table1] WHERE [ID] = ?");
                stmt.setInt(1, aList.getItem(itemId).getBean().getID());

                rs = stmt.executeQuery();
            //if the row is already there, update the data/

                if (rs.isBeforeFirst()){
                    System.out.println("Duplicate");
                    stmt2 = con2.prepareStatement("UPDATE [DB].[dbo].[Table1] SET "
                    + "[DateSelected]=GETDATE() where  [ID] = ?");
                    stmt2.setInt(1,aList.getItem(itemId).getBean().getID());
                stmt2.executeUpdate();
                }//end if inserting duplicate
                else{
                    con2 = cpds2.getConnection();
                    System.out.println("Insertion");
                    stmt.setInt(1, aList.getItem(itemId).getBean().getID());

                    //Otherwise, insert them as if they were new
                    stmt2 = con.prepareStatement("INSERT INTO [DB].[dbo].[Table1] ([ID],[FirstName],"
                            + "[LastName],[DateSelected]) VALUES (?,?,?,?)");
                    stmt2.setInt(1,aList.getItem(itemId).getBean().getID() );
                    stmt2.setString(2,aList.getItem(itemId).getBean().getFirstName());
                    stmt2.setString(3,aList.getItem(itemId).getBean().getLastName() );
                    stmt2.setTimestamp(4, new Timestamp(new Date().getTime()));
                    stmt2.executeUpdate();
                }//End Else
        }catch(Exception e){
                e.printStackTrace();
            }//End Catch
        finally{
                try { if (rs!=null) rs.close();} catch (Exception e) {}
            try { if (stmt2!=null) stmt2.close();} catch (Exception e) {}
            try { if (stmt!=null) stmt.close();} catch (Exception e) {}
            try { if (con2!=null) con2.close();} catch (Exception e) {}
            try {if (con!=null) con.close();} catch (Exception e) {}
            }//End Finally

    } //end for loop
    Notification.show("Save Complete");

这是我的汇集连接:

    //Pooled connection
    cpds2 = new ComboPooledDataSource();

    try {
        cpds2.setDriverClass("net.sourceforge.jtds.jdbc.Driver");
    } catch (PropertyVetoException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } //loads the jdbc driver
    cpds2.setJdbcUrl( "jdbc:jtds:sqlserver://SERVERNAME;instance=DB" );
    cpds2.setUser("username");
    cpds2.setPassword("password"); 
    cpds2.setMaxStatements( 180 ); 
    cpds2.setDebugUnreturnedConnectionStackTraces(true); //To help debug
    cpds2.setUnreturnedConnectionTimeout(2);  //to help debug

我的主要问题是,我正在关闭我的联系吗?我的连接池设置正确吗? 我应该关闭for循环内部还是外部的连接?

我的问题是c3p0吗?还是JTDS?

1 个答案:

答案 0 :(得分:1)

你努力谨慎地close()你的资源,这很好,但这太复杂了。

除非您使用相当旧版本的Java(Java 7之前的版本),否则可以使用try-with-resources,这可以真正简化这些内容。在一个逻辑工作单元中使用两个不同的连接会引起误解。资源应尽可能在本地使用close(),而不是将所有内容推迟到最后。

您的异常处理很危险。如果发生了您不理解的异常,您可能希望打印其堆栈跟踪,但您的代码应该表明无论您在做什么都不起作用这一事实。您吞下Exception,甚至通知“Save Complete”。

所有这一切都说明了MERGE语句I think SQL Server supports可以使你的生活变得更轻松。

这是一个(未经测试,未编译的)示例重组:

try ( Connection con = cpds2.getConnection() ) {
    for (Object itemId: aList.getItemIds()){
        boolean id_is_present = false;
        try ( PreparedStatement stmt = con.prepareStatement("select [ID] from [DB].[dbo].[Table1] WHERE [ID] = ?") ) {
            stmt.setInt(1, aList.getItem(itemId).getBean().getID());
            try ( ResultSet rs = stmt.executeQuery() ) {
               id_is_present = rs.next();
            }
        }
        if ( id_is_present ) {
            System.out.println("Duplicate");
            try ( PreparedStatement stmt = con.prepareStatement("UPDATE [DB].[dbo].[Table1] SET [DateSelected]=GETDATE() where  [ID] = ?") ) {
                stmt.setInt(1,aList.getItem(itemId).getBean().getID());
                stmt.executeUpdate();
            }
         } else {
             System.out.println("Insertion");
             try ( PreparedStatement stmt = con.prepareStatement("INSERT INTO [DB].[dbo].[Table1] ([ID],[FirstName], [LastName],[DateSelected]) VALUES (?,?,?,?)") ) {
                 stmt.setInt(1,aList.getItem(itemId).getBean().getID() );
                 stmt.setString(2,aList.getItem(itemId).getBean().getFirstName());
                 stmt.setString(3,aList.getItem(itemId).getBean().getLastName() );
                 stmt.setTimestamp(4, new Timestamp(new Date().getTime()));
                 stmt.executeUpdate();
             }
         }
    }
    Notification.show("Save Complete");    
}