Sending Java objects to a database

To send an instance of a user-defined class as column data, use one of the following setObject methods, as specified in the PreparedStatement interface:

void setObject(int parameterIndex, Object x, int targetSqlType, 
   int scale) throws SQLException;
void setObject(int parameterIndex, Object x, int targetSqlType) 
   throws SQLException;
void setObject(int parameterIndex, Object x) throws SQLException;

In jConnect, to send a Java object, you can use the java.sql.Types.JAVA_OBJECT target sql.Type, or you can use java.sql.Types.OTHER.

The following example defines an Address class, shows the definition of a Friends table that has an Address column whose datatype is the Address class, and inserts a row into the table.

public class Address implements Serializable
{
  public String   streetNumber;
   public String   street;
   public String   apartmentNumber;
   public String   city;
   public int   zipCode;
  //Methods
  ...
}

/* This code assumes a table with the following structure
**  Create table Friends:
**  (firstname varchar(30)  , 
**   lastname varchar(30), 
**  address Address, 
**  phone varchar(15))
*/

// Connect to the database containing the Friends table.
Connection conn = 
   DriverManager.getConnection("jdbc:sybase:Tds:localhost:5000", 
     "username", "password");
 
// Create a Prepared Statement object with an insert statement 
//for updating the Friends table.
PreparedStatement ps = conn.prepareStatement("INSERT INTO 
   Friends values (?,?,?,?)");
 
// Now, set the values in the prepared statement object, ps.
// set firstname to "Joan."
ps.setString(1, "Joan");
 
// Set last name to "Smith."
ps.setString(2, "Smith");
 
// Assuming that we already have "Joan_address" as an instance
// of Address, use setObject(int parameterIndex, Object x) to 
// set the address column to "Joan_address."
ps.setObject(3, Joan_address);
 
// Set the phone column to Joan’s phone number.
ps.setString(4, "123-456-7890");
 
// Perform the insert.
ps.executeUpdate();