接着上一讲的内容,直接看下面的代码。
①将blob类型的数据写入数据库中:
/**
* 将blob类型的数据写入数据库中
* @param student
* @return
* @throws Exception
*/
public static int addStudent(Student student) throws Exception{
Connection conn = dbUtils.getConnetction(); //获取数据库连接
String sql = "insert into zhanghua values(null,?,?,?,?)"; //执行数据库sql的写法
PreparedStatement psmt = conn.prepareStatement(sql); //获取prepareStatement对象
psmt.setString(1, student.getUserName()); //设置第一个参数的值
psmt.setInt(2, student.getAge()); //设置第二个参数的值
//将clob类型字段写入数据库中
File file = student.getContent(); //获取大文件
InputStream inputStream = new FileInputStream(file);
psmt.setAsciiStream(3, inputStream,file.length()); //设置第三个参数值
//将blob类型字段写入数据库中
File file_pic = student.getPic(); //获取图片
InputStream inputStream_pic = new FileInputStream(file_pic);
psmt.setBinaryStream(4, inputStream_pic, file_pic.length()); //设置第四个参数的值
int result = psmt.executeUpdate();
dbUtils.close(psmt, conn);
return result;
}
②从数据库中读取blob类型的字段,并存在本地:
/**
* 通过id查询学生
* @param id
* @throws Exception
*/
public static void findStudentById(int id) throws Exception{
Connection conn = dbUtils.getConnetction(); //获取数据库连接
String sql = "select * from zhanghua where id = ?"; //执行数据库sql
PreparedStatement psmt = conn.prepareStatement(sql); //获取prepareStatement对象
psmt.setInt(1, id);
ResultSet rs = psmt.executeQuery();
if(rs.next()){
String username = rs.getString("username"); //学生姓名
int age = rs.getInt("age"); //年龄
//从数据库中读取clob类型的字段
Clob clob = rs.getClob("content"); //获取大文本
String content = clob.getSubString(1, (int)clob.length());
//从数据库中读取blob类型的字段
Blob blob = rs.getBlob("pic");
OutputStream out = new FileOutputStream(new File("D:/22.JPG"));
out.write(blob.getBytes(1,(int)blob.length()));
System.out.println("学生姓名为: "+ username);
System.out.println("学生年龄: "+ age);
System.out.println("大文本: "+ content);
}
dbUtils.close(psmt, conn);
}