This question is related to my question on Stack Overflow earlier today. After getting suggestions on using the PreparedStatement
from Java I changed my code a little.
EDIT: In my original question on Stack Overflow I attempted to process the query in a very messy way, see this short excerpt:
String sqlQuerry = "INSERT INTO TASKS " + "VALUES (" + table.getValueAt(i, 0) + ", " + table.getValueAt(i, 1) + ", " + table.getValueAt(i, 2) + ", " + table.getValueAt(i, 3) + ", "
Even though this might have worked, it would have been harder to understand and I ran into issues when the
table.getValueAt(X,Y)
returned "null".
As I am completely new to SQL in Java I want to know if the code below is "good" or at least "okayish" and can be maintained later on. If you got any tips on how to make this cleaner, let me know.
String sqlInsert = "INSERT INTO TASKS " + "VALUES" + "(?,?,?,?,?,?,?,?,?,?,?,?,?)";
for (int i = 0; i < table.getModel().getRowCount(); i++) {
PreparedStatement sqlState = conn.prepareStatement(sqlInsert);
int j = 1;
sqlState.setInt(j++, Integer.parseInt(table.getValueAt(i, 0).toString()));
sqlState.setInt(j++, Integer.parseInt(table.getValueAt(i, 1).toString()));
sqlState.setInt(j++, Integer.parseInt(table.getValueAt(i, 2).toString()));
sqlState.setInt(j++, Integer.parseInt(table.getValueAt(i, 3).toString()));
sqlState.setString(j++, table.getValueAt(i, 4).toString());
sqlState.setString(j++, table.getValueAt(i, 5).toString());
sqlState.setString(j++, table.getValueAt(i, 6).toString());
sqlState.setString(j++, table.getValueAt(i, 7).toString());
sqlState.setInt(j++, Integer.parseInt(table.getValueAt(i, 8).toString()));
sqlState.setString(j++, table.getValueAt(i, 9).toString());
sqlState.setString(j++, table.getValueAt(i, 10).toString());
sqlState.setString(j++, table.getValueAt(i, 11).toString());
sqlState.setBoolean(j++, (boolean) table.getValueAt(i, 12));
sqlState.executeUpdate();
}