JDBC学习笔记(4)——操作BLOB类型字段
1.MySQL BLOB类型
2.向数据表中插入和查找Blob
插入数据调用方法:setBlob()
connection = JDBCUtils.getConnection();
String sql = "insert into customers(name,email,birth,photo) values (?,?,?,?)";
preparedStatement = connection.prepareStatement(sql);
preparedStatement.setObject(2,"90798@gmail.com");
preparedStatement.setObject(3,"1972-12-16");
FileInputStream is = new FileInputStream(new File("111.png"));
preparedStatement.setBlob(4,is);
preparedStatement.execute();
查找数据调用getBlob():
Blob photo = resultSet.getBlob("photo");
//将Blob类型的字段下载下来以文件方式保存在本地
is = photo.getBinaryStream();
fos = new FileOutputStream("张宇.jpg");
byte[] buffer = new byte[1024];
int len;
while ((len = is.read()) !=-1 ){
fos.write(buffer,0,len);
}
3. 批量插入数据的操作
//使用批操作方法:addBatch()、executeBatch()、clearBatch()减少数据库的访问次数
connection = JDBCUtils.getConnection();
//设置不允许自动提交数据
connection.setAutoCommit(false);
String sql = "insert into goods(name)values(?)";
preparedStatement = connection.prepareStatement(sql);
for (int i = 1; i <= 20000; i++) {
preparedStatement.setObject(1, i);
//1.攒sql
preparedStatement.addBatch();
if (i%500 == 0){
//2.执行batch
preparedStatement.executeBatch();
//3.清空batch
preparedStatement.clearBatch();
}
}
//提交数据
connection.commit();