Manage tables and data

2023-12-14 07:26:05  Updated

OceanBase Connector/J allows you to modify database tables and data by using DML and DDL operations.

DML operations

To perform an INSERT or UPDATE operation, create a Statement or PreparedStatement object. You can use the PreparedStatement object to run a statement with a set of input parameters. The prepareStatement method of a Connection object can define a statement, bind variables to parameters, and return a PreparedStatement object with a statement definition.

The PreparedStatement object uses the setXXX method to bind data to a statement to be sent to the database.

Example: Use the PreparedStatement object to perform the INSERT operation to add two rows of data to the customers table.

PreparedStatement ps = null;
try{
    ps = conn.prepareStatement ("insert into customers (customerID, name) values (?, ?)");
    ps.setInt (1, 150);                 // The first question mark (?) corresponds to customerID.
    ps.setString (2, "Adam");     // The second question mark (?) corresponds to name.
    ps.execute ();
    ps.setInt (1, 207);           
    ps.setString (2, "Alice");   
    ps.execute ();
}

finally{
     if(ps!=null)
     ps.close();
}

DDL operations

To perform a DDL operation, create a Statement or PreparedStatement object.

Example: Use a Statement object to create a table in the database.

// Create the customers table and the customerID and name columns.

String query;
Statement st=null;
query="create table customers " +
          "(customerID int, " +
          "name varchar(50))";
st = conn.createStatement();
st.executeUpdate(query);
st.close();    // Close the statement.

If a DDL operation needs to be performed again, a new DDL statement must be prepared.

Example: Prepare a DDL statement before a DDL operation is performed again.

PreparedStatement ps = null;
PreparedStatement ts = null;
ps = conn.prepareStatement ("insert into customers(customerID, name) values (?, ?)");   // The first question mark (?) corresponds to customerID. The second question mark (?) corresponds to name.
ps.setInt (1, 150);            // Add a new customer whose name is Adam and ID is 150.
ps.setString (2, "Adam");      
ps.execute ();    
ts = conn.prepareStatement("truncate table customers");
ts.executeUpdate();
ps.setInt (1, 207);            // Add a new customer whose name is Alice and ID is 207.
ps.setString (2, "Alice");      
ps.execute ();
ts.close();
ts = conn.prepareStatement("truncate table customers");
ts.executeUpdate();
if(ps!=null)
     ps.close();     // Close the statement.

Contact Us