Sunday, February 14, 2010

Reading a Class using BLOB from a MySQL Database

MySQL does not directly have the capacity to handle java classes. However, an instance of a class can be converted to a BLOB which can then be stored. The following is a sample program doing that:


public class SampleClass {

static final String DataBase_Url =
"jdbc:mysql://localhost:3306/myDatabase";
static final String Driver = "com.mysql.jdbc.Driver";

//note the Driver will always be the same when
connecting to MySQL but the URL is dependent on
your MySQl database: localhost is the Server Host,
3306 is the port and samptable is the name of the schema

public static void main(String[] args) {
String printStr = "This is your concience speaking.";
System.out.println(printStr);

Connection con = null;
Statement stat = null;
ResultSet rSet = null;
try
{
Class.forName(Driver);
con = DriverManager.getConnection(DataBase_Url,
"username", "secretPassword");
stat = con.createStatement();

rSet = stat.executeQuery("SELECT username from user");
System.out.println("\nUsernames");

while (rSet.next()) {
String ferrariprice = rSet.getString("username");
System.out.println(" " + ferrariprice );
}

}

catch (Exception Exc)
{
Exc.printStackTrace();
System.err.println(Exc.getMessage());
}

finally
{
try
{
rSet.close();
stat.close();
con.close();
}
catch (SQLException sqlExc)
{
sqlExc.printStackTrace();
}
}//end finally

//Pull Blob
stat = null;
rSet = null;
con = null;

//Connection conn = DBUtil.getConnection(connectionName);

try {

Class.forName(Driver);
con =
DriverManager.getConnection(DataBase_Url, "username", "secretPassword");
stat = con.createStatement();

rSet = stat.executeQuery("SELECT * FROM savedcasing");
System.out.println("got rSet");

while (rSet.next()) {
try {
com.faneng.workflow.model.SavedCasingVO
vo = new com.faneng.workflow.model.SavedCasingVO();
vo.setId(rSet.getInt("id"));
vo.setSavedCurveId(rSet.getInt("savedCurveId"));
Blob ib = rSet.getBlob("casingInputVO");
ByteArrayInputStream is = null;
ObjectInputStream ins = null;

if (ib != null) {
is = new ByteArrayInputStream(ib.getBytes(1, (int)
ib.length()));
ins = new ObjectInputStream(is);
vo.setCasingInputVO((CasingInputVO)
ins.readObject());
vo.getCasingInputVO().getDiameter());
}

} catch (Exception e) {
throw new SQLException(e.getMessage());
}
}
}
catch (Exception Exc)
{
Exc.printStackTrace();
System.err.println(Exc.getMessage());
}

finally
{
try
{
rSet.close();
stat.close();
con.close();
}
catch (SQLException sqlExc)
{
sqlExc.printStackTrace();
}
}//end finally

}

}

No comments:

Post a Comment

JSP - Java Description

https://docs.oracle.com/javaee/5/tutorial/doc/bnair.html