Extreme slow update SQL with image in Java I have a database of 70,000 records. For each record in the database I have to put images in PNG format. I need to loop and update all the records.
String url = "jdbc:sqlserver://" + dbServer + ";databaseName=" + dbName + ";user=" + dbUser + ";password=" + dbPassword + "";
Connection link = DriverManager.getConnection(url);
Statement stmt = link.createStatement();

ResultSet row = stmt.executeQuery("SELECT * FROM postal_codes");

while(row.next()){
  File imageFile = new File("C:\\res\\flags\\" + filename + ".png");
  String query = "UPDATE postal_codes SET flag = ?  WHERE ID = ?";
  PreparedStatement preStmt = link.prepareStatement(query);
  preStmt.setBinaryStream(1, new FileInputStream(imageFile), (int)imageFile.length());
  preStmt.setInt(10, row.getInt("ID"));
  preStmt.executeUpdate();
}

I executed this script and it's already 14 minutes of execution and the loop is at a 30,000 record!
I have an identically working script in PHP and Python. In those languages, the script takes up to ~300 seconds to finish all records.
What am I doing wrong?
PHP ~ 280 seconds
foreach ($rows as $row) {
  $fileData = file_get_contents('res/flags/'.$filename.'.png');
  $stmt = $db->prepare('UPDATE postal_codes SET flag = :flag  WHERE ID = '.$row['ID'].'');
  $stmt->bindParam(':flag', $fileData, PDO::PARAM_LOB, 0, PDO::SQLSRV_ENCODING_BINARY);
  $stmt->execute();
}

Python ~ 190 seconds
for row in cursor.fetchall():
  image = open('../res/flags/' + filename + '.png', 'rb')
  image_data = image.read()
  image.close()
  cursor.execute("UPDATE postal_codes SET flag = ? ....... WHERE ID = ?", image_data, row.ID)
  conn.commit()

The value under the variable "filename" may be different. That's why I have to loop all records.

Prepare the statement outside the loop and, most importantly, use a transaction instead of committing after each row, because "By default, new connections are in autocommit mode." -- setAutocommit()