public class ReadWriteBigData {
/*
create database bigdata;
use bigdata;
create table bigdata //创建表
(
id varchar(20)primary key,
pinglun text,(大数据)
image blob(二进制)
);*/
public void insert()
{
try{
Connection con=DBHelper.getConnection();
String sql="insert into bigdata(id,pinglun) value(?,?)";
PreparedStatement ps=con.prepareStatement(sql);
ps.setString(1, "A001");
//存取大文本,用preparedStatement对象方法读到流中去
File f=new File("src//mysql/1.txt");
FileReader reader=new FileReader(f);
ps.setCharacterStream(2, reader,f.length());
//ps.setBinaryStream(parameterIndex, x, length);//插入图像等二进制
int i=ps.executeUpdate();
if(i>0)
{
System.out.println("insert success");
}}
catch (Exception e) {
System.out.println("fail.....");
}
}
@Test
public void test() throws FileNotFoundException, SQLException
{
ReadWriteBigData r=new ReadWriteBigData();
r.insert();
}
}
package mysql;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import org.junit.Test;
//preparedStatement.addBatch()处理批处理只能执行一种sql语句(插入,更新。。),多个数据的表复制
//preparedStetement用的比较多
//statement.addBatch()能处理多条sql,能同时插入,更新删除。。
//批处理数据,如果处理插入100万条数据,不能一次插入100万条数据
//可以用for循环,没插入1000条addBatch(),然后clearBatch()在插入
public class batch {
@Test
public void test1() throws SQLException {
Connection con=null;
PreparedStatement ps=null;
con = DBHelper.getConnection();
String sql = "insert into login(username,password) values(?,?)";
ps = con.prepareStatement(sql);
for(int i=0;i<10;i++)
{
ps.setString(1, i+"");
ps.setString(2, i+"");
ps.addBatch();//批处理,内部装在list集合中
}
ps.executeBatch();//一次性执行批处理代码
}
@Test
public void test2() throws SQLException
{
//分批次处理100万条数据,每次执行1000条,在addBatch(),在clearBatch(),不然会内存漏出
long a=System.currentTimeMillis();
Connection con=null;
PreparedStatement ps=null;
con = DBHelper.getConnection();
String sql = "insert into login(username,password) values(?,?)";
ps = con.prepareStatement(sql);
for(int i=201;i<2000;i++)
{
ps.setString(1, i+"");
ps.setString(2, i+"");
ps.addBatch();
if(i%1000==0)//每次加入1000条数据
{
ps.executeBatch();//批处理,先执行1000次
ps.clearBatch();//先加入的数据清空
}
}
ps.executeBatch();//执行批处理代码
System.out.println("the time execute is"+(System.currentTimeMillis()-a));
}
}