【问题标题】:Database is not getting updated after executing this program执行此程序后数据库未更新
【发布时间】:2014-04-11 10:00:19
【问题描述】:

这里是代码

import java.sql.*;

public class Insertdb {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        try
        {
            Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
        Connection con= DriverManager.getConnection("jdbc:odbc:Dsn1");
        PreparedStatement ps= con.prepareStatement("insert into Table1 values (?,?,?)");
        ps.setInt(1,1);
        ps.setString(2,"Sachin");
        ps.setInt(3,25000);
        int i=ps.executeUpdate();
        if(i>0)
        {
            System.out.println(i +"records inserted");
        }

        }
        catch(Exception e)
        {
            System.out.println(e);
        }

        // TODO code application logic here
    }
}

使用的数据库是 MS Access 2013。 上面代码在控制台的输出是:1条记录插入

但是当我打开数据库时,并没有插入记录。代码有什么问题吗?如果不是,会出现什么问题?

【问题讨论】:

  • 可能你需要提交事务
  • 如何提交事务?
  • 关闭所有连接、结果集和语句,然后检查。
  • 感谢@xwhyz。实际上我禁用了自动提交并使用了 con.commit()。它就像魅力一样。

标签: java ms-access jdbc


【解决方案1】:

最后还要加上。

finally{
    con.commit();
    ps.close();
    con.close();
    }

【讨论】:

    【解决方案2】:

    从程序到数据库的任何事务都必须提交才能反映在 JAVA 中。 尝试做 con.commit();

    【讨论】:

      【解决方案3】:

      如果您正在连接数据库或执行文件操作,请尝试在您的代码中使用 finally。因为无论 try 块上发生什么,finally 块总是执行。所以您可以使用 finally 块来关闭数据库连接并关闭文件并提交或回滚数据库记录。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-12-02
        • 2012-03-09
        • 1970-01-01
        • 1970-01-01
        • 2015-12-25
        相关资源
        最近更新 更多