首先说明下我们实验的条件:
数据库中的表:books ,字段id(int) book(Blob二进制流)
连接方式:JDBC
定义一个简单的连接数据库的类:
public class DataBase{
public static final String Driver = "com.mysql.jdbc.Driver";
public static final String url = "jdbc:mysql://localhost:3306/books";
public static final String user = "root";
public static final String password = "root";
static {
try {
Class.forName(Driver);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
public static Connection getConnection() throws SQLException{
Connection conn = null;
conn = DriverManager.getConnection(url,user,password);
return conn;
}
}
其次,定义测试类,我们使用ArrayList对象来实验,为了方便我们将异常进行抛出
class Test{
public static void main(String[] args) throw Exception{
ArrayList al = new ArrayLIst();
al.add("1");
al.add("2");
al.add("3");
//先进行数据的保存
Connection conn = DataBase.getConnection();
PreparedStatement pstmt = con.prepareStatement("insert into books values(1,?)");//想数据库中插入第一组数据
pstmt.setObject(1,al);
int time = pstmt.executeUpdate();//执行操作
System.out.println(time+"插入完成");//提示插入完成
pstmt.close();
//再进行数据的提出
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("select book from books where id=1");
if(rs.next()){
ObjectInputStream oips = new ObjectInputStream(rs.getBinaryStream(1));
//从rs中得到对象的流,如果直接从rs.getObject(1)得到的对象是无法直接转化为下面的对象的。
ArrayList obb = (ArrayList)oips.readObject();//从流中读取对象
System.out.println(obb.get(2));//输出对象中指定的数据
oips.close();
}
rs.close();
stmt.close();
con.close();
}
}