简体   繁体   中英

Updating SQL Server Table from a jTable

I have a jTable in my Java application. which is directly filled from an SQL Server table (No Join) The user has the ability to add/delete/update rows. if the user press on the save button all the performed changes on the jTable should be committed on the database.

What is the best approach to implement such user operation? (deleting and inserting back is not an option)

You can queue your statements (ie: DELETE, UPDATE, INSERT, etc.) into a list based on the actions performed on the local JTable . Once the save button is pressed, you can iterate through each query statement in the list and commit the changes to your SQL Server:

List<String> listOfStatements = new ArrayList<String>();

Connection connection = new SQLServerDataSource().getConnection();
Statement statement = connection.createStatement();
connection.setAutoCommit(false);

for(String query : listOfStatements) {
    statement.executeUpdate(query);
}

connection.commit();
connection.setAutoCommit(true);
connection.close();

You should make sure that not more than one user is trying to change the database with this method or you may run into problems.

Also, you should use PreparedStatements if SQL injection is of concern to you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM