当前位置:Gxlcms > 数据库问题 > 数据库存储txt文本和jpg图片

数据库存储txt文本和jpg图片

时间:2021-07-01 10:21:17 帮助过:60人阅读

环境:MySql+SQLyog+j2se+jdbc

存储文本用longtext类型

存储图片用blob类型

1、首先建表

create table t_t (
id int(16) NOT NULL AUTO_INCREMENT,
longText longtext,
picture blob,
PRIMARY KEY (`id`)
) ;

`longText` longtext,//文本txt
`picture` blob,//图片pic

技术分享

 

数据库为t_test,表为t_t

2、jdbc操作,打开eclipse for j2se

  1. String jdbcName="com.mysql.jdbc.Driver";
  2. String dbUrl="jdbc:mysql://localhost:3306/t_test";
  3. String dbUserName="root";
  4. String dbPassword="123456";
  5. Class.forName(jdbcName);//加载驱动
  6. Connection conn=DriverManager.getConnection(dbUrl,dbUserName,dbPassword);//连接
  7. //构造第一个SQL语句,先不管图片,先插入文本
  8. String sql="insert into t_t values(NUll,?,NULL)";//?为第一个坑
  9. PreparedStatement pst=conn.prepareStatement(sql);

找材料:

在E盘建立两个TXT文档

技术分享

  随便写一些文字,先不考虑有中文。

  

  1. File context=new File("e:/h01.txt");//File文件
  2. InputStream inputStream=new FileInputStream(context);//使用流
  3. pst.setAsciiStream(1,inputStream,context.length());//填第一个坑
  4. int result=pst.executeUpdate();//执行SQL语句
  5. if(result==1){//提示信息
  6. System.out.println("插入成功");
  7. }else{
  8. System.out.println("插入失败");
  9. }

  有一些异常用 throws抛出(throws ClassNotFoundException, SQLException, FileNotFoundException)

技术分享

 

转到数据库,看到插入了一个文本

技术分享

取出文本,

  1. String sql="select * from t_t where id=?";//挖坑?
  2. PreparedStatement pst=conn.prepareStatement(sql);
  3. pst.setInt(1, 1);//第一个1是填第一个坑,第二个1是数据库中id为1的记录
  4. ResultSet rs=pst.executeQuery();
  5. if(rs.next()){
  6. Clob c=rs.getClob("longText");//使用Clob
  7. String str=c.getSubString(1, (int)c.length());//赋值给字符串
  8. System.out.println(str);//输出文本
  9. }

  运行如下:

技术分享

结果与h01.txt的结果一致

图片picture的存储

  在E盘准备一张图片(002.jpg)

  1. //不考虑txt(设置为NULL)只考虑jpg
  2. String sql="insert into t_t values(NUll,NULL,?)";//挖坑
  3. PreparedStatement pst=conn.prepareStatement(sql);
  4. File pic=new File("e:/002.jpg");
  5. InputStream inputStream=new FileInputStream(pic);
  6. pst.setBinaryStream(1, inputStream,pic.length());//填坑
  7. int result=pst.executeUpdate();
  8. if(result==1){//提示信息
  9. System.out.println("插入成功");
  10. }else{
  11. System.out.println("插入失败");
  12. }

  eclipse插入成功,看数据库。

技术分享

技术分享

002.jpg已经插入到了数据库

下一步

取出图片到F盘

  1. String sql="select picture from t_t where id=?";//挖坑
  2. PreparedStatement pst=conn.prepareStatement(sql);
  3. pst.setInt(1,2);//填坑,2表示数据库的id=2的这条记录
  4. ResultSet rs=pst.executeQuery();
  5. if(rs.next()){
  6. Blob b=rs.getBlob("picture");
  7. //输出到F盘并且命名为003.jpg
  8. FileOutputStream out=new FileOutputStream(new File("f:/003.jpg"));
  9. out.write(b.getBytes(1, (int)b.length()));
  10. out.close();
  11. }
  12. conn.close();

  运行成功,F盘多了一个003.jpg与002.jpg相同

数据库存储txt文本和jpg图片

标签:操作   sql   信息   statement   stream   dbus   文件   cli   .com   

人气教程排行