一、操作Blob
- BLOB是一个二进制大型对象,是一个可以存储大量数据的容器。
- 插入BLOB类型数据必须使用PreparedStatement,因为BLOB类型的数据时无法使用字符串拼接写的。
- 四种BLOB:TinyBlob 最大255字节;Blob 65K;MediumBlob 16M;LongBlob 4G
import com.atguigu3.util.JDBCUtils;
import com.mysql.jdbc.Blob;
import org.junit.Test;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
public class BlobTest {
//向数据表customers中插入Blob类型的字段
@Test
public void testInsert() throws Exception
{
Connection conn= JDBCUtils.getConnection();
String sql="insert into customers(name,email,birth,photo)values(?,?,?,?)";
PreparedStatement ps=conn.prepareStatement(sql);
ps.setObject(1,"zjx");
ps.setObject(2,"zjx@qq.com");
ps.setObject(3,"1999-10-1");
FileInputStream is=new FileInputStream(new File("testpic.JPG"));
ps.setBlob(4,is);
ps.execute();
JDBCUtils.closeResource(conn,ps);
}
//查询数据表中Blob类型字段
@Test
public void testQuery() throws Exception
{
Connection conn=JDBCUtils.getConnection();
String sql="select id,name,email,birth,photo from customers where id=?";
PreparedStatement ps = conn.prepareStatement(sql);
ps.setObject(1,19);
ResultSet resultSet = ps.executeQuery();
if(resultSet.next())
{
// //方式一
// int id=resultSet.getInt(1);
// String name=resultSet.getString(2);
// String email=resultSet.getString(3);
// Date birth=resultSet.getDate(4);
//方式二
int id=resultSet.getInt("id");
String name=resultSet.getString("name");
String email=resultSet.getString("email");
Date birth=resultSet.getDate("birth");
Customer cust=new Customer(id,name,email,birth);
System.out.println(cust);
//将Blob类型的字段下载下来,保存在本地
Blob photo= (Blob) resultSet.getBlob("photo");
InputStream is=photo.getBinaryStream();
FileOutputStream fos=new FileOutputStream("testDownload.jpg");
byte[] buffer=new byte[1024];
int len;
while((len=is.read(buffer))!=-1)
{
fos.write(buffer,0,len);
}
is.close();
fos.close();
}
JDBCUtils.closeResource(conn,ps);
}
}
二、批量插入数据
使用PreparedStatement实现批量数据的操作
update、delete本身就具有批量操作的效果(不写where的限制条件就会操作许多)
但insert一条条操作,此时批量操作主要指的是批量插入。
- 循环+PreparedStatement
- 攒一攒sql
@Test
public void testInsert2() throws Exception
{
Connection conn= JDBCUtils.getConnection();
String sql="insert into goods(name)values(?)";
PreparedStatement ps = conn.prepareStatement(sql);
for(int i=1;i<=20000;i++)
{
ps.setObject(1,"name_"+i);
//攒 sql
ps.addBatch();
if(i%500==0)
{
//执行batch
ps.executeBatch();
//清空batch
ps.clearBatch();
}
}
JDBCUtils.closeResource(conn,ps);
}
- 还可以设置不允许自动提交,最后一起提交(插入)数据。
@Test
public void testInsert2() throws Exception
{
Connection conn= JDBCUtils.getConnection();
conn.setAutoCommit(false);
String sql="insert into goods(name)values(?)";
PreparedStatement ps = conn.prepareStatement(sql);
for(int i=1;i<=20000;i++)
{
ps.setObject(1,"name_"+i);
//攒 sql
ps.addBatch();
if(i%500==0)
{
//执行batch
ps.executeBatch();
//清空batch
ps.clearBatch();
}
}
//提交数据
conn.commit();
JDBCUtils.closeResource(conn,ps);
}