Java中的ExecuteUpdate sql语句不起作用

时间:2016-10-27 16:35:34

标签: java sql jdbc

我正在学习如何在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");
}

这是我非常简单的数据库的图像: enter image description here

虽然没有进行任何数据库更改,但控制台中的结果如下:

数据库已成功打开

1

数据库已成功关闭

提前致谢!

2 个答案:

答案 0 :(得分:8)

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

或者

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

  

禁用自动提交模式后,没有SQL语句   提交,直到您明确调用方法提交。所有陈述   在上一次调用方法提交之后执行的操作包含在   当前的交易并作为一个整体共同承诺。

答案 1 :(得分:0)

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

事实证明,您cannot在同一批中执行两个不同语句(或PreparedStatements)。

我遇到了同样的问题,没有错误,没有异常,数据库记录根本无法按需更新。

重新使用以前使用的PreparedStatement解决了该问题。