Gamer Gamer - 7 months ago 46
Java Question

CachedRowset acceptChanges not working after insert opertion

I am using MyQL 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();
}
}
}


Please let me know how make it work.

Answer

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