mysql怎么把文字图片保存在一起_MySQL存储文本和图片的方法

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

}

}

}

总结

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

本文标题: MySQL存储文本和图片的方法

本文地址: http://www.cppcns.com/shujuku/mysql/253800.html

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值