📄 serializer.java
字号:
//声明本类包含在包examples.jdbc.informix4中
package examples.jdbc.informix4;
//声明本类要引入的其他包和类
import java.io.*;
import java.sql.*;
import java.util.Properties;
/**
*
* 这个实例演示怎样插入数据到Informix BLOB 列
* 它演示这些通过序列化一个对象,并存入到数据库中。
*/
public class serializer {
//主方法
public static void main(String args[]) {
//JDBC类
java.sql.Connection conn = null;
java.sql.Statement stmt = null;
java.sql.ResultSet rs = null;
java.sql.PreparedStatement pstmt = null;
try {
//属性对象
Properties props = new Properties();
props.put("user", "informix");
props.put("password", "secret");
props.put("server", "myDBHost");
props.put("port", "1493");
props.put("db", "myDB");
//加载驱动程序
Driver myDriver = (Driver) Class.forName("weblogic.jdbc.informix4.Driver").newInstance();
//建立数据库连接
conn = myDriver.connect("jdbc:weblogic:informix4", props);
//创建声明
stmt = conn.createStatement();
try {
//执行SQL语句,删除表
stmt.execute("drop table blobtest");
System.out.println("Dropped table blobtest");
}
catch (SQLException e) {
// 删除的表不存在
}
//创建表
stmt.execute("create table blobtest (foo byte)");
System.out.println("creating blobtest table");
// 创建一个要序列化的类实例
aClass a = new aClass(1234);
//把对象流转化成一个字节数组
System.out.println("Created aClass with value 1234");
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream (baos);
oos.writeObject(a);
byte[] aBytes = baos.toByteArray();
// 把字节数组写到数据表
pstmt = conn.prepareStatement("insert into blobtest(foo) values (?)");
pstmt.setBinaryStream(1, new ByteArrayInputStream(aBytes),aBytes.length);
pstmt.executeUpdate();
System.out.println("Inserted aClass into the database");
a = null;
aBytes = null;
// 再把写入的对象读出来
rs = stmt.executeQuery("select foo from blobtest");
rs.next();
ObjectInputStream ois = new ObjectInputStream(rs.getBinaryStream(1));
aClass newa = (aClass)ois.readObject();
System.out.println("Retrieved the aClass object from the database with value " + newa.getVal());
} catch (Exception e) {
//异常
System.out.println("Caught Exception: " + e.getMessage());
} finally {
//关闭数据库
try {
if (stmt != null)
stmt.close();
if (pstmt != null)
pstmt.close();
if (rs != null)
rs.close();
if (conn != null)
conn.close();
} catch (SQLException sqle) {
System.out.println("SQLExcption was thrown: " + sqle.getMessage());
}
}
}
}
/**
* 这个类实现接口serializable。用来进行序列化操作
*/
class aClass implements Serializable {
int aValue;
public aClass(int v) { aValue = v; }
public int getVal() { return aValue; }
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -