将大数据写入数据库

来源:互联网 发布:淘宝虚拟现实vr购物 编辑:程序博客网 时间:2024/05/16 11:47

将大数据写入数据库

主要知识点:
1、在数据库中建立合适的表
2、与读取数据库中的大数据;

在数据库中建立合适的表

/* * CLOB: Character Large Object   最大上限就是4G   1) 有4种TEXT类型:TINYTEXT、TEXT、MEDIUMTEXT和LONGTEXT。这些对应4种BLOB类型   2) BLOB是一个二进制大对象,可以容纳可变数量的数据。有4种BLOB类型:TINYBLOB、BLOB、MEDIUMBLOB和LONGBLOB。它们只是可容纳值的最大长度不同。演示大数据对象所用数据库表的脚本:CREATE TABLE note(  id INT PRIMARY KEY,  note TEXT   //能保存65535个字符);CREATE TABLE img(  id INT PRIMARY KEY,  img BLOB     //img MediumBLOB );TinyBLOB最大支持255B, BLOB最大只支持65K, MediumBLOB最大只支持16M, LongBLOB最大支持4G*/``保存与读取:-------

//保存大数据,只能使用PreparedStatement。 用Statement是无法实现的!
public class LobDemo {

@Test //保存大文本数据对象到数据库public void ClobSave() throws Exception{    Connection con = ConnUtils.getConn();    String sql = "insert into note values(?,?)";    PreparedStatement pst = con.prepareStatement(sql);    pst.setInt(1, 1);    //pst.setString(2, "aaaa"); //用该方法直接传入 字符串变量 是不行的,因为数据太大,占内存太多    //必须用Ascii码流来设置大文本数据字段的参数    File file = new File("src/cn/hncu/res/ResultSetDemo.java");    InputStream in = new FileInputStream(file);    pst.setAsciiStream(2, in);//※※※※    pst.executeUpdate();    con.close();}

@Test //读取数据库中的大文本数据对象
public void ClobRead() throws Exception{
Connection con = ConnUtils.getConn();
String sql = “select * from note where id=1”;
Statement st = con.createStatement();
ResultSet rs = st.executeQuery(sql);
rs.next();

    InputStream in = rs.getAsciiStream(2); //大文本字段,用ASCII流的方式读取    //自己写代码从in中把数据读取出来    BufferedReader br = new BufferedReader(new InputStreamReader(in));    String str = null;    while( (str=br.readLine())!=null){        System.out.println(str);    }    con.close();}

@Test //保存大二进制数据对象(如图片)到数据库
public void BlobSave() throws Exception{
Connection con = ConnUtils.getConn();
String sql = “insert into img values(?,?)”;
PreparedStatement pst = con.prepareStatement(sql);
pst.setInt(1, 1);

    //必须用Ascii码流来设置大文本数据字段的参数    File file = new File("d:/a/1.png");    InputStream in = new FileInputStream(file);    pst.setBinaryStream(2, in);//※※※※    pst.executeUpdate();    con.close();}

@Test //读取数据库中的大二进制数据对象(如图片)
public void BlobRead() throws Exception{
Connection con = ConnUtils.getConn();
String sql = “select * from img where id=1”;
Statement st = con.createStatement();
ResultSet rs = st.executeQuery(sql);
rs.next();

    InputStream in = rs.getBinaryStream(2);//※※※※    OutputStream out = new FileOutputStream("D:/a/a.png");    byte buf[] = new byte[512];    int len=0;    while( (len=in.read(buf))!=-1){        out.write(buf, 0, len);    }    in.close();    out.close();    con.close();        }

“`

原创粉丝点击