Benoit Goderre Benoit Goderre - 1 month ago 4
Java Question

ExecuteUpdate sql statement in Java not working

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:
enter image description here

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

Database opened successfully

1

Database closed successfully

Thanks in advance!

Answer

Remove c.setAutoCommit(false) line from open database

Or

Add c.commit() for end of updateSchool method

Comments