当前位置: 移动技术网 > IT编程>数据库>Mysql > MySQL存储文本和图片的方法

MySQL存储文本和图片的方法

2019年03月19日  | 移动技术网IT编程  | 我要评论

oracle中大文本数据类型

clob  长文本类型  (mysql中不支持,使用的是text)
blob  二进制类型

mysql数据库

text   长文本类型
  tinytext:   256 bytes
  text:     65,535 bytes    => ~64kb
  mediumtext:  16,777,215 bytes  => ~16mb
  longtext:   4,294,967,295 bytes => ~4gb
blob  二进制类型

例如:

建表

create table test(
   id int primary key auto_increment,
   content longtext, -- 文本字段
   img longblob  -- 图片字段
);

存储文本时是以字符类型存储,存储图片时是以二进制类型存储,具体使用的设置参数方法,和获取数据方法不同。

例如:

// 存储文本时
// 存储时,设置参数为字符流 filereader reader
pstmt.setcharacterstream(1, reader);
// 获取参数时
// 方式1:
reader r = rs.getcharacterstream("content");
// 获取长文本数据, 方式2:
system.out.print(rs.getstring("content"));
// 存储二进制图片时 
// 设置参数为2进制流 inputstream in 
pstmt.setbinarystream(1, in);
// 获取2进制流
inputstream in = rs.getasciistream("img");
/**
 * 保存照片
 * 
 */
@test
public void test2(){
  string sql = "insert into test(img) values(?)";
  try{
    con = jdbcutil.getconnection();
    pstmt = con.preparestatement(sql);
    // 设置参数
    // 获取文本
    file file = new file("f:/a.jpg");
    inputstream in = new fileinputstream(file);
    // 设置参数为2进制流
    pstmt.setbinarystream(1, in);
    // 执行sql
    pstmt.executeupdate();
    in.close();
  }catch (exception e) {
    e.printstacktrace();
  }finally{
    try {
      jdbcutil.close(con, pstmt);
    } catch (exception e) {
      // todo auto-generated catch block
      e.printstacktrace();
    }
  }
}
/**
 * 获取照片
 * 
 */
@test
public void test3(){
  string sql = "select * from test where id=?;";
  try{
    con = jdbcutil.getconnection();
    pstmt = con.preparestatement(sql);
    // 设置参数
    pstmt.setint(1, 2);
    // 执行查询
    rs = pstmt.executequery();
    while(rs.next()){
      byte[] buff = new byte[1024];
      inputstream in = rs.getasciistream("img");
      int l=0;
      outputstream out = new fileoutputstream(new file("f:/1.jpg"));
      while((l=in.read(buff))!=-1){
        out.write(buff, 0, l);
      }
      in.close();
      out.close();
    }
  }catch (exception e) {
    e.printstacktrace();
  }finally{
    try {
      jdbcutil.close(con, pstmt);
    } catch (exception e) {
      // todo auto-generated catch block
      e.printstacktrace();
    }
  }
}

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对移动技术网的支持。如果你想了解更多相关内容请查看下面相关链接

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网