SQL Structured Type:

creating user define types in database to store address details.
create type address as Object(dno number, street varchar2(10),city varchar2(10),state varchar2(10));
creating table with struct as column type :
create table Student(sno number,sname varchar2(10),com_address address);
for every struct in DB we should define a class which is-a type of SQLData.
Insert records:
import java.sql.*;
class Address implements SQLData{
int dno;
String street,city,state;
String typename;
void setDno(int dno){
this.dno=dno;
}
void setStreet(String street){
this.street=street;
}
void setTypeName(String s){
typename=s;
}
void setCity(String city){
this.city=city;
}
void setState(String state){
this.state=state;
}
int getDno(){
return dno;
}
String getStreet(){
return street;
}
String getCity(){
return city;
}
String getState(){
return state;
}
public Address(){
}
public void writeSQL(SQLOutput so)throws SQLException{
so.writeInt(dno);
so.writeString(street);
so.writeString(city);
so.writeString(state);
}
public void readSQL(SQLInput si, String name)throws SQLException{
dno=si.readInt();
street=si.readString();
city=si.readString();
state=si.readString();
typename=name;
}
public String getSQLTypeName(){
return typename;
}
}
class InsertStudentData_Struct{
public static void main(String[] args)throws Exception {
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:XE","advjava","advjava");
PreparedStatement ps=con.prepareStatement("insert into student values(?,?,?)");
ps.setInt(1,10);
ps.setString(2,"Abhi");

Address adr=new Address();
adr.setDno(201);
adr.setStreet("AmeerPet");
adr.setCity("Hyderabad");
adr.setState("AP");
adr.setTypeName("ADDRESS");

ps.setObject(3,adr);
ps.executeUpdate();
System.out.println("Record inserted Successfully");
ps.close();
con.close();
}}


Retrieve records:
ResultSet rs=st.executeQuery("select sname,com_address from student where sno=10");
if(rs.next()){
System.out.println(rs.getString(1));
Struct stru=(Struct)rs.getObject(2);
Object addr[]=stru.getAttributes();
System.out.println("Dno:"+addr[0]);
System.out.println("Street:"+addr[1]);
System.out.println("City:"+addr[2]);
System.out.println("State:"+addr[3]);}

No comments:

Post a Comment