百分百源码网-让建站变得如此简单! 登录 注册 签到领金币!

主页 | 如何升级VIP | TAG标签

当前位置: 主页>网站教程>数据库> MySQL存储文本和图片的要领
分享文章到:

MySQL存储文本和图片的要领

发布时间:05/13 来源:未知 浏览: 关键词:

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();
    }
  }
}

总结

以上就是这篇文章的全部内容了,但愿本文的内容对大家的学习或者工作拥有一定的参考学习价值,感谢大家对脚本之家的支撑。要是你想理解更多相干内容请查看下面相干链接

打赏

打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,你说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

百分百源码网 建议打赏1~10元,土豪随意,感谢您的阅读!

共有158人阅读,期待你的评论!发表评论
昵称: 网址: 验证码: 点击我更换图片
最新评论

本文标签

广告赞助

能出一分力是一分吧!

订阅获得更多模板

本文标签

广告赞助

订阅获得更多模板