ExecuteUpdate sql statement in Java not working

北城以北 提交于 2020-12-08 06:37:08

问题


I am learning how to use SQL with Java. I have installed the JDBC driver successfully and I am able to read the records from a database and print it on the screen.

My problem occurs when trying to do either an update or insert statement, where nothing happens. Here is my code:

Method where the problem resides

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);
    }
}

Support functions

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");
}

Here is an image of my very simple database:

The result in the console is the following, although no databases changes were done:

Database opened successfully

1

Database closed successfully

Thanks in advance!


回答1:


Remove c.setAutoCommit(false) line from the openDatabase method.

Or

Add c.commit() at the end of the updateSchool method.

After the auto-commit mode is disabled, no SQL statements are committed until you call the method commit explicitly. All statements executed after the previous call to the method commit are included in the current transaction and committed together as a unit.




回答2:


The OP's query has been solved, but this might help someone.

It turns out that you cannot execute two different Statements(or PreparedStatements) in a single batch.

I was having the same problem, no errors, no exceptions, the database record simply wouldn't update as it should.

Resusing the previously used PreparedStatement solved the problem.



来源:https://stackoverflow.com/questions/40289951/executeupdate-sql-statement-in-java-not-working

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!