怎么在MySQL中存储文本和图片

36次阅读
没有评论

共计 1968 个字符,预计需要花费 5 分钟才能阅读完成。

自动写代码机器人,免费开通

本篇文章为大家展示了怎么在 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 中存储文本和图片,你们学到知识或技能了吗?如果还想学到更多技能或者丰富自己的知识储备,欢迎关注丸趣 TV 行业资讯频道。

向 AI 问一下细节

正文完
 
丸趣
版权声明:本站原创文章,由 丸趣 2023-12-04发表,共计1968字。
转载说明:除特殊说明外本站除技术相关以外文章皆由网络搜集发布,转载请注明出处。
评论(没有评论)