c3p0 CombopooledDataSource不提交SQL更新

时间:2014-11-20 10:17:10

标签: java sql c3p0

我正在使用池化数据源(msaccess数据库)通过我创建的应用程序更新本地数据库(客户端使用h2数据库)。 我遇到的问题是提交请求时说'#34; INSERT INTO USERS(NAME,CODE)VALUES(Me,hfd5255fd4);"应用程序运行完美,错误日志中没有报告任何内容但数据库中没有任何更改。 我使用的代码如下

private static Connection getDatabase() throws Exception {


    cpds.setDriverClass("net.ucanaccess.jdbc.UcanaccessDriver");
    // loads the jdbc driver
    cpds.setJdbcUrl("jdbc:ucanaccess://"
            + (new File("Ressources/filter.mdb").getAbsolutePath()));
    cpds.setUser("admin");
    cpds.setPassword("ibnsina");
    cpds.setAutoCommitOnClose(false);
 return cpds.getConnection(); //tried removing this , but no effect
}
----doing some other stuff---
private static updating() throws exception{
conn = getDatabase();

    File fileUpload = new File(logPath + "UploadLog.txt");
    BufferedReader readerUpload = new BufferedReader(new FileReader(
            fileUpload));
    String Uploadingline = "";
    StringBuffer secondaryline = new StringBuffer();
    if (readerUpload.ready()) {
        System.out.println("Uploadtxt ready");
        Statement stUpload = conn.createStatement();
        System.out.println("Stupload ready");
        while ((Uploadingline = readerUpload.readLine()) != null) {

            if (Uploadingline.endsWith(";")) {
                secondaryline.append(Uploadingline);
                /*stUpload.executeUpdate(secondaryline.toString()); tried this to execute each line separatly*/
                stUpload.addBatch(secondaryline.toString());
                System.out.println("Reading line :" + secondaryline);
                secondaryline.setLength(0);

            } else {
                secondaryline.append(Uploadingline);

            }

        }
        stUpload.executeBatch();
        stUpload.clearBatch();
        conn.commit(); //i even tried adding this to make it commit even tho autocommit is by default ON
        stUpload.close();}

1 个答案:

答案 0 :(得分:2)

您不应为每个连接创建新的DataSource,只需创建一个DataSource并使用它来获取Connection。请记住close(),因为它会返回与池的连接。

您应该执行以下操作:

// There should only ever be one of these.
private static final DataSource ds = makeDataSource();

private static DataSource makeDataSource() {
    ComboPooledDataSource cpds = new ComboPooledDataSource();
    cpds.setDriverClass("net.ucanaccess.jdbc.UcanaccessDriver");
    // loads the jdbc driver
    cpds.setJdbcUrl("jdbc:ucanaccess://"
            + (new File("Ressources/filter.mdb").getAbsolutePath()));
    cpds.setUser("admin");
    cpds.setPassword("ibnsina");
    cpds.setAutoCommitOnClose(false);
    return cpds;
}

private static Connection getConnection () {
    return ds.getConnection();
}

private static void releaseConnection (Connection conn) {
    conn.commit();
    conn.close();
}

private static void updating() {
    Connection conn = getConnection();
    try {
        //...
    } finally {
        releaseConnection(conn);
    }
}