【问题标题】:ExecuteUpdate sql statement in Java not workingJava中的ExecuteUpdate sql语句不起作用
【发布时间】:2017-03-10 10:52:38
【问题描述】:

我正在学习如何在 Java 中使用 SQL。我已经成功安装了 JDBC 驱动程序,我可以从数据库中读取记录并将其打印在屏幕上。

我的问题发生在尝试执行更新或插入语句时,但没有任何反应。这是我的代码:

问题所在的方法

public static void updateSchools(ArrayList<String> newSchool)
{
    try
    {
        openDatabase();
        stmt = c.createStatement();
        int numberOfRows = stmt.executeUpdate("UPDATE schools SET address='abc' WHERE abbreviation='2';");
        System.out.println(numberOfRows);
        closeDatabase();
    }
    catch (Exception e)
    {
        System.err.println(e.getClass().getName() + ": " + e.getMessage());
        System.exit(0);
    }
}

支持功能

public static void openDatabase()
{
    c = null;
    stmt = null;
    try
    {
        Class.forName("org.postgresql.Driver");
        c = DriverManager.getConnection("jdbc:postgresql://localhost:5432/Badminton", "postgres", "postgrespass");
        c.setAutoCommit(false);
    }
    catch (Exception e)
    {
        System.err.println(e.getClass().getName() + ": " + e.getMessage());
        System.exit(0);
    }
    System.out.println("Database opened successfully");
}

public static void closeDatabase()
{
    try
    {
        stmt.close();
        c.close();
    }
    catch (Exception e)
    {
        System.err.println(e.getClass().getName() + ": " + e.getMessage());
        System.exit(0);
    }
    System.out.println("Database closed successfully");
}

这是我非常简单的数据库的图像:

控制台中的结果如下,尽管没有进行数据库更改:

数据库打开成功

1

数据库关闭成功

提前致谢!

【问题讨论】:

  • 不要使用“;”它可以破坏sql;你有什么例外吗?
  • 你需要刷新你的数据库,或者提交c.setAutoCommit(True);
  • @karelss 来自 Postgres documentation: Get in the habit of including those SQL semicolons
  • 学习“尝试资源”。
  • try(Connection con = getConnection(url, username, password, "org.postgresql.Driver"); Statement stmt = con.createStatement(); ResultSet rs = stmt.executeQuery(sql); ) { //statements }catch(....){} 在此处阅读更多信息 stackoverflow.com/questions/2225221/…

标签: java sql jdbc


【解决方案1】:

openDatabase 方法中删除c.setAutoCommit(false) 行。

或者

updateSchool 方法的末尾添加c.commit()

禁用自动提交模式后,没有 SQL 语句 提交,直到您显式调用方法提交。所有陈述 在上一次调用方法 commit 之后执行的包含在 当前事务并作为一个单元一起提交。

【讨论】:

  • 非常感谢,我的代码现在可以按预期工作了 :)。
  • 解释为什么这会解决问题只会为您的答案添加一点额外内容。
  • 我的插入和更新查询没有提交到数据库,这就是我看不到任何更改的原因。一旦我在操作后添加了提交行,更改就成功完成了。
【解决方案2】:

OP 的查询已解决,但这可能对某人有所帮助。

原来你cannot在一个批次中执行了两个不同的语句(或PreparedStatements)。

我遇到了同样的问题,没有错误,没有异常,数据库记录根本不会按应有的方式更新。

重用之前使用的 PreparedStatement 解决了这个问题。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-28
    • 2012-03-25
    • 1970-01-01
    相关资源
    最近更新 更多