package utils;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Calendar;
public class JdbcTest {
public static void main(String[] args) throws IOException {
People p = new People();
p.setName("测试");
p.setAge(10);
p.setBirthday(Calendar.getInstance().getTime());
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(bos);
oos.writeObject(p);
Connection con = null;
PreparedStatement stm = null;
ResultSet res =null;
try {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("数据库url", "用户名", "密码");
stm = con.prepareStatement("insert into people (people) value(?)");
stm.setBytes(1, bos.toByteArray());
stm.executeUpdate();
stm = con.prepareStatement("select id,people from people limit 1");
res = stm.executeQuery();
while(res.next()){
System.out.println(res.getInt(1));
ByteArrayInputStream bis = new ByteArrayInputStream(res.getBytes(2));
ObjectInputStream ois = new ObjectInputStream(bis);
People pn = (People)ois.readObject();
System.out.println(pn.getName());
System.out.println(pn.getAge());
System.out.println(pn.getBirthday());
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}finally{
try {
res.close();
stm.close();
con.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
package utils;
import java.io.Serializable;import java.util.Date;public class People implements Serializable{ /*** */private static final long serialVersionUID = 1L;private String name;private int age;private Date birthday;public String getName() { return name;}public void setName(String name) { this.name = name;}public int getAge() { return age;}public void setAge(int age) { this.age = age;}public Date getBirthday() { return birthday;}public void setBirthday(Date birthday) { this.birthday = birthday;}}MYSQL:字段设置为blob的格式即可。自己测试完全可以。