Rumah > Artikel > pangkalan data > JDBC大数据存取_MySQL
//大数据存取,程序一般不把大文本或二进制数据保存到数据库;
//大数据分为clob 用于存储文本; blob 用于存储 二进制数据,如图像,声音, 二进制文件。
// Mysql 没有clob,只有TEXT;
1. 封装连接数据工具类
2 大数据存取
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.Reader;
import java.io.Writer;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.junit.Test;
public class CloabDemo {
@Test
public void add(){
Connection conn = null;
PreparedStatement pstmt = null;
try {
conn = JdbcUtil.getConnection();//
String sql = "insert into t1(id,content) values(?,?) ";
pstmt = JdbcUtil.prepare(conn, sql);
pstmt.setInt(1, 1);
//大数据 要使用流的形式
File file = new File("d:/clob.txt");
Reader reader = new FileReader(file);
pstmt.setCharacterStream(2, reader, (int)file.length()); //不能使用long的参数, mysql支持不到那么大的数据
int i =pstmt.executeUpdate();
if(i>0){
System.out.println("插入成功");
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally{
JdbcUtil.closeConn(conn, pstmt, null);
}
}
//读
@Test
public void read(){
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
try {
conn = JdbcUtil.getConnection();//
String sql = "select * from t1 where id =?";
pstmt = conn.prepareStatement(sql);
pstmt.setInt(1, 1);
//大数据 要使用流的形式
//保存到E盘
rs=pstmt.executeQuery(sql);
if(rs.next()){
Reader reader = rs.getCharacterStream("content");
Writer writer = new FileWriter("E:/clob.txt");
char[] c = new char[1024];
int len =-1;
while ((len=reader.read(c))!=-1){
writer.write(c, 0, len);
}
reader.close();
writer.close();
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally{
JdbcUtil.closeConn(conn, pstmt, null);
}
}
}