Saturday, 21 January 2017

OBJECT

If database table created with column type as objects, it can hold more than one value of different types. Syntax - 
create type <typename> as object (<columnname> <type>, <columnname> <type>......);

SQL> create type add_type as object(street varchar2(20), city varchar2(20));

SQL> create table person(name varchar2(20), address add_type);


SQLData

It is an interface. The interface used for custom mapping of an SQL user-defined type (UDT) to a class in the java programming language. The class object for a class implementing the SQLData interface will be entered in the appropriate connection objects type map along with the SQL name of the UDT for which it is a custom mapping.

Methods
  1. String getSQLTypeName() - Returns fully qualified name of the SQL user-defined type that this object represents.
  2. void readSQL(SQLInput stream, String typename) - Populates this object with data read from the database.
  3. void writeSQL(SQLOutput stream) - Writes this object to the given SQL data stream, converting it back to its SQL value in the data source.

PROGRAM TO INSERT RECORD USING OBJECT IN DATABASE

package Package1;
import java.sql.*;
public class Address implements SQLData{
private String street;
private String city;
private String sqltype;
public Address(String street, String city, String sqltype) {
super();
this.street = street;
this.city = city;
this.sqltype = sqltype;
}
@Override
public String getSQLTypeName() throws SQLException {
return sqltype;
}
@Override
public void readSQL(SQLInput stream, String typeName) throws SQLException {
street=stream.readString();
city=stream.readString();
this.sqltype=sqltype;
}
@Override
public void writeSQL(SQLOutput stream) throws SQLException {
stream.writeString(street);
stream.writeString(city);
}
}

-------------------------------------------------------

package Package1;
import Package1.Address;
import java.sql.*;
public class WriteObjectTest {
public static void main(String[] args) throws ClassNotFoundException, SQLException {
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:orcl", "scott", "rakesh");
PreparedStatement ps = con.prepareStatement("insert into person values(?,?)");
ps.setString(1,"rakesh");
Address a = new Address("Bamunimaidam", "Guwahati", "ADD_TYPE");
ps.setObject(2, a);
int count=ps.executeUpdate();
System.out.println(count);
}
}

Output -
NAME
--------------------
ADDRESS(STREET, CITY)

rakesh
ADD_TYPE('Bamunimaidam', 'Guwahati')

No comments:

Post a Comment