简体   繁体   中英

How can update a JdbcRowSet object?

I want to execute the following SQL command with one JdbcRowSet object:

INSERT INTO Authors (FirstName,LastName) VALUES ('Sue', 'Smith')

I know that i can execute with Connection and Satements objects, but i want to do this with the interface JdbcRowSet, because one JdbcRowSet object is updatable and scrollable by default.

My code is:

public class JdbcRowSetTest
{
    public static final String DATABASE_URL = "jdbc:mysql://localhost/books";
    public static final String USERNAME = "Ezazel";
    public static final String PASSWORD = "Ezazel";

    public JdbcRowSetTest()
    {
        try
        {
            JdbcRowSet rowSet = new JdbcRowSetImpl();
            rowSet.setUrl( DATABASE_URL );
            rowSet.setUsername( USERNAME );
            rowSet.setPassword( PASSWORD );
            rowSet.setCommand( "INSERT INTO Authors (FirstName,LastName) VALUES ('Sue', 'Smith')" );
            rowSet.execute();
        }
        catch( SQLException e )
        {
        }
    }

    public static void main( String[] args )
    {
        JdbcRowSetTest app = new JdbcRowSetTest ();
    }
}

SQLException error:

java.sql.SQLException: Can not issue data manipulation statements with executeQuery().
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1086)
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:989)
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:975)
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:920)
    at com.mysql.jdbc.StatementImpl.checkForDml(StatementImpl.java:502)
    at com.mysql.jdbc.PreparedStatement.executeQuery(PreparedStatement.java:2224)
    at com.sun.rowset.JdbcRowSetImpl.execute(JdbcRowSetImpl.java:582)
    at JdbcRowSetTest.(JdbcRowSetTest.java:23)
    at JdbcRowSetTest.main(JdbcRowSetTest.java:53)

You can't use a JdbcRowSet to execute insert statements like that. If that is what you want, then you should use a normal Statement or PreparedStatement instead.

The RowSet.setCommand is for queries only:

Sets this RowSet object's command property to the given SQL query. This property is optional when a rowset gets its data from a data source that does not support commands, such as a spreadsheet.
Parameters:
cmd - the SQL query that will be used to get the data for this RowSet object; may be null

If you really want to use a row set, then you can update or insert new rows in the way documented for an updatable ResultSet :

Updating:

to update a column value in the current row. In a scrollable ResultSet object, the cursor can be moved backwards and forwards, to an absolute position, or to a position relative to the current row. The following code fragment updates the NAME column in the fifth row of the ResultSet object rs and then uses the method updateRow to update the data source table from which rs was derived.

 rs.absolute(5); // moves the cursor to the fifth row of rs rs.updateString("NAME", "AINSWORTH"); // updates the // NAME column of row 5 to be AINSWORTH rs.updateRow(); // updates the row in the data source 

For inserting:

to insert column values into the insert row. An updatable ResultSet object has a special row associated with it that serves as a staging area for building a row to be inserted. The following code fragment moves the cursor to the insert row, builds a three-column row, and inserts it into rs and into the data source table using the method insertRow .

 rs.moveToInsertRow(); // moves cursor to the insert row rs.updateString(1, "AINSWORTH"); // updates the // first column of the insert row to be AINSWORTH rs.updateInt(2,35); // updates the second column to be 35 rs.updateBoolean(3, true); // updates the third column to true rs.insertRow(); rs.moveToCurrentRow(); 

Note that the reference implementation of javax.sql.rowset in my experience regularly doesn't work as expected. You might be better off using plain JDBC.

You are missing execute() :

To query using "Select" statement and return a JdbcRowSet:

public void createJdbcRowSet(String url, String username, String password, String sql) {
    jdbcRs = new JdbcRowSetImpl();
    jdbcRs.setCommand(sql);
    jdbcRs.setUrl(url);
    jdbcRs.setUsername(username);
    jdbcRs.setPassword(password);
    jdbcRs.execute();
    // ...
}

Update:
Once you have the returned JdbcRowSet, you can insert a new row as this example shows:

public void updateJdbcRowSet(String username, String password) {
    jdbcRs.moveToInsertRow();
    jdbcRs.updateString("USERNAME", "NewUser");
    jdbcRs.updateString("PASSWORD", "ENCRYPTED");
    jdbcRs.insertRow();
}
public static void main(String[] args) {

        try {
            RowSetFactory rowset =RowSetProvider.newFactory();
            JdbcRowSet jdbcrow=rowset.createJdbcRowSet();
            jdbcrow.setUrl(BD_Url);
            jdbcrow.setUsername(DB_User);   
            jdbcrow.setPassword(DB_password);
//this is your database connectivity like uername,password and url and
 driver in not imp in mysql 5.1.23 jar file 

            jdbcrow.setCommand("Select * from Demo");
            jdbcrow.execute();
//uppere parts is use to fetch the record from table



   System.out.println("--------------------Insert----------");
    jdbcrow.moveToInsertRow();
    jdbcrow.updateInt("ID", 115);
    jdbcrow.updateString("Username","Hitesh");
    jdbcrow.updateString("Password","Sir");
    jdbcrow.insertRow();

//The down code is used for update the value

System.out.println("=--------------------Update-------------------------");
jdbcrow.absolute(3);// 3rd row
jdbcrow.updateString("Password","Sirs" ); //colname password 
jdbcrow.updateRow();

For Delete you can use

System.out.println("=-----------Delete-----------------------------");



    while (jdbcrow.next()) {  
            String id=jdbcrow.getString("Id"); 
         //here i getting  ID  record from my table
          System.out.println("s"   +id);
            if(id.equals("102")) { 
            //then i my Specifying that if my table iD is .eqauls to 102 then delete 
              that record you also used this type to updatetbale

                 jdbcrow.deleteRow();
                System.out.println("gaye");
                break;
            }
        }
        //if record delete then preform `enter code here`some operation

//this is used to delete last record from table

System.out.println("=---------------delete-------------------------");
    jdbcrow.last();
    jdbcrow.deleteRow();

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