Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CachedRowset acceptChanges not working after insert opertion

I am using MySQL database and I have a table Employee with 2 columns: Id (Int; Primary Key) and Name (String). I have written some code to insert a row into the Employee table, but the acceptChanges is not working and the code stops at acceptChanges. The code is as follows :

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

import javax.sql.rowset.CachedRowSet;
import javax.sql.rowset.RowSetFactory;
import javax.sql.rowset.RowSetProvider;

public class InsertSynchronizer {

    static CachedRowSet crs = null;

    public static void main(String[] args) {

        try {
            Class.forName("com.mysql.jdbc.Driver");
            Connection c = DriverManager.getConnection("jdbc:mysql://localhost:3306/", "root", "");
            c.setAutoCommit(false);
            RowSetFactory myRowSetFactory = null;
            myRowSetFactory = RowSetProvider.newFactory();
            crs = myRowSetFactory.createCachedRowSet();
            crs.setUrl("jdbc:mysql://localhost:3306/test");
            crs.setUsername("root");
            crs.setPassword("");
            crs.setConcurrency(CachedRowSet.CONCUR_UPDATABLE);
            crs.setCommand("select * from employee");
            crs.execute();
            while (crs.next()) {
                System.out.println(crs.getString("Name"));
            }

            // Inserting rows
            crs.moveToInsertRow();
            crs.updateInt("Id", 5);
            crs.updateString("Name", "E");
            crs.insertRow();

            //Thread.sleep(60000);
            crs.acceptChanges(c); // Updating Data Sources

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

1 Answers

The statement crs.moveToCurrentRow() have to be added after crs.insertRow() and before crs.acceptChanges(c)

For example:

 // Inserting rows
crs.moveToInsertRow();
crs.updateInt("Id", 5);
crs.updateString("Name", "E");
crs.insertRow();
crs.moveToCurrentRow(); // NEW STATEMENT
crs.acceptChanges(c); // Updating Data Sources

For more information visit: http://docs.oracle.com/javase/tutorial/jdbc/basics/cachedrowset.html#inserting-and-deleting-rows

like image 69
Dmytro Plekhotkin Avatar answered Dec 06 '25 17:12

Dmytro Plekhotkin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!