mysql 存入 blob类型数据

本文涉及的产品
云数据库 RDS MySQL Serverless,0.5-2RCU 50GB
简介: mysql 存入 blob类型数据   最佳 解决方案 如果是字符串 的 blob  , 在 bean 中 把 该字段 设置成 byte[]  即可,遇到汉字 不会乱码 如果是文件 可以采用下面方法。

mysql 存入 blob类型数据

 

最佳 解决方案

如果是字符串 的 blob  , 在 bean 中 把 该字段 设置成 byte[]  即可,遇到汉字 不会乱码

如果是文件 可以采用下面方法。

 

 

 

 

 方案一

把String类型转为Blob类型很简单,只要将 newSerialBlob(String对象的.getBytes())就可以获得一个Blob对象,

 要是把Blob对象转为String 一种是new String(Blob.getBytes(0,Blob对象.length)) 可是在开发中这样是不行了,总提示一个错误,只有获得Blob对象的输入流才可以

 IntputStream is = Blob对象.getBinaryStream()在用该对的read()方法读取一个字节数组在转换为String

 

 

 方案二

1、在类中定义大字段:

Java代码   收藏代码
  1. public class informAffiche {  
  2.    private Blob content;  
  3.   
  4.   
  5. public void setcontent(Blob S_content)  
  6. {  
  7. content=S_content;  
  8. }  
  9. public Blob getcontent()  
  10. {  
  11. return content;  
  12. }  
  13.   
  14. }  

 

2、数据库中读取大字段内容并set进去:

Java代码   收藏代码
  1. while(rs.next())  
  2.     {  
  3. s.setcontent(rs.getBlob("content"));  
  4. }  

 

3、在页面得到

 

Java代码   收藏代码
  1. if (list.size()>0){  
  2.    s=(informAffiche)list.get(0);  
  3.  Blob blob= s.getcontent();  
  4.   
  5. if(blob == null || blob.length()==0){  
  6.     content = "";  
  7.   }else{  
  8.     content = new String(blob.getBytes((long)1, (int)blob.length()));  
  9.     System.out.println("content---->"+content);  
  10.   }  
  11.   
  12.   
  13. }  

 

4、页面输出:

<td><%=content  %></td>

 

 

 

 方案三

package org.util;  
import java.io.BufferedInputStream;  
import java.io.BufferedOutputStream;  
import java.io.File;  
import java.io.FileInputStream;  
import java.io.FileNotFoundException;  
import java.io.FileOutputStream;  
import java.io.IOException;  
import java.io.InputStream;  
import java.io.InputStreamReader;  
import java.io.OutputStream;  
import java.sql.Connection;  
import java.sql.PreparedStatement;  
import java.sql.ResultSet;  
import java.sql.SQLException;  
public class BlobTest {  
    /** 
     * @param args 
     * @throws SQLException  
     * @throws IOException  
     */  
    public static void main(String[] args) throws SQLException, IOException {  
        // TODO Auto-generated method stub  
        //create();  
        read(2);  
    }  
      
    //将二进制流存储入数据库blob字段类型。  
    public static void create() throws SQLException, IOException{  
        String sql = "insert into blob_test values(id,?)";  
          
        Connection conn = null;  
        PreparedStatement ps = null;  
          
        try{  
            conn = JdbcUtil.getInstance().getConnection();  
            ps = conn.prepareStatement(sql);  
            File file = new File("input_text_right.gif");  
            BufferedInputStream in = new BufferedInputStream(new FileInputStream(file));  
            ps.setBlob(1, in);  
            int id = ps.executeUpdate();  
            System.out.println("id:"+id);  
            in.close();  
        }finally{  
            JdbcUtil.free(null, ps, conn);  
        }  
    }  
      
    //读取二进制流,并写入新的文件  
    public static void read(int id) throws SQLException, IOException{  
        String sql = "select big_bit from blob_test where id=? limit 1";  
          
        Connection conn = null;  
        PreparedStatement ps = null;  
        ResultSet rs = null;  
        try{  
            conn = JdbcUtil.getInstance().getConnection();  
            ps = conn.prepareStatement(sql);  
            ps.setInt(1, id);  
            rs = ps.executeQuery();  
              
            byte[] b = new byte[1024];  
            while(rs.next()){  
                InputStream in = rs.getBinaryStream(1);//InputStream是字节输入流的所有类的超类  
                File file = new File("left.gif");  
                BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(file));//BufferedOutputStream是缓冲的输出流  
                  
                for(int i=0; (i=in.read(b))>0;){//read方法接收byte数组,并将数据存储在缓冲数组b中  
                    out.write(b);//将指定的字节写入此缓冲的输出流。  
                }  
                out.close();//关闭此输出流并释放与此流有关的所有系统资源。  
            }  
              
              
        }finally{  
            JdbcUtil.free(rs, ps, conn);  
        }  
    }  
} 

 

 

public class PostJdbcDao extends JdbcDaoSupport implements PostDao {
private LobHandler lobHandler;
private DataFieldMaxValueIncrementer incre;
public LobHandler getLobHandler() {
   return lobHandler;
}
public void setLobHandler(LobHandler lobHandler) {
   this.lobHandler = lobHandler;
}
public void addPost(final Post post) {  
   String sql = " INSERT INTO t_post(post_id,user_id,post_text,post_attach)"
     + " VALUES(?,?,?,?)";
   getJdbcTemplate().execute(
     sql,
     new AbstractLobCreatingPreparedStatementCallback(
       this.lobHandler) {
      protected void setValues(PreparedStatement ps,
        LobCreator lobCreator) throws SQLException {
       ps.setInt(1, incre.nextIntValue()); 
       ps.setInt(2, post.getUserId()); 
       lobCreator.setClobAsString(ps, 3, post.getPostText());
       lobCreator.setBlobAsBytes(ps, 4, post.getPostAttach());
      }
     });
}
}

 

 

 方案四

<bean id="nativeJdbcExtractor"
   class="org.springframework.jdbc.support.nativejdbc.CommonsDbcpNativeJdbcExtractor"
   lazy-init="true" />
<bean id="oracleLobHandler"
   class="org.springframework.jdbc.support.lob.OracleLobHandler"
   lazy-init="true">
   <property name="nativeJdbcExtractor" ref="nativeJdbcExtractor" />
</bean>
<bean id="dao" abstract="true">
   <property name="jdbcTemplate" ref="jdbcTemplate" />
</bean>
<bean id="postDao" parent="dao"
   class="com.baobaotao.dao.jdbc.PostJdbcDao">
   <property name="lobHandler" ref="oracleLobHandler" />
</bean>
Oracle 10g或其他数据库如下设置:
<bean id="defaultLobHandler"
   class="org.springframework.jdbc.support.lob.DefaultLobHandler"
   lazy-init="true" />
<bean id="dao" abstract="true">
   <property name="jdbcTemplate" ref="jdbcTemplate" />
</bean>
<bean id="postDao" parent="dao"
   class="com.baobaotao.dao.jdbc.PostJdbcDao">
   <property name="lobHandler" ref="defaultLobHandler" />
</bean>

 

 

public List getAttachs(final int userId){
   String sql = "SELECT post_id,post_attach FROM t_post where user_id =? and post_attach is not null";
   return getJdbcTemplate().query(
       sql,new Object[] {userId},
       new RowMapper() {
        public Object mapRow(ResultSet rs, int rowNum) throws SQLException {
        Post post = new Post();
        int postId = rs.getInt(1);
         byte[] attach = lobHandler.getBlobAsBytes(rs, 2);
         post.setPostId(postId);
         post.setPostAttach(attach);
         return post;
        }
       });
}

 

 

 

 

 

 

 

 

相关实践学习
基于CentOS快速搭建LAMP环境
本教程介绍如何搭建LAMP环境,其中LAMP分别代表Linux、Apache、MySQL和PHP。
全面了解阿里云能为你做什么
阿里云在全球各地部署高效节能的绿色数据中心,利用清洁计算为万物互联的新世界提供源源不断的能源动力,目前开服的区域包括中国(华北、华东、华南、香港)、新加坡、美国(美东、美西)、欧洲、中东、澳大利亚、日本。目前阿里云的产品涵盖弹性计算、数据库、存储与CDN、分析与搜索、云通信、网络、管理与监控、应用服务、互联网中间件、移动服务、视频服务等。通过本课程,来了解阿里云能够为你的业务带来哪些帮助 &nbsp; &nbsp; 相关的阿里云产品:云服务器ECS 云服务器 ECS(Elastic Compute Service)是一种弹性可伸缩的计算服务,助您降低 IT 成本,提升运维效率,使您更专注于核心业务创新。产品详情: https://www.aliyun.com/product/ecs
目录
相关文章
|
9天前
|
缓存 NoSQL 关系型数据库
13- Redis和Mysql如何保证数据⼀致?
该内容讨论了保证Redis和MySQL数据一致性的几种策略。首先提到的两种方法存在不一致风险:先更新MySQL再更新Redis,或先删Redis再更新MySQL。第三种方案是通过MQ异步同步以达到最终一致性,适用于一致性要求较高的场景。项目中根据不同业务需求选择不同方案,如对一致性要求不高的情况不做处理,时效性数据设置过期时间,高一致性需求则使用MQ确保同步,最严格的情况可能涉及分布式事务(如Seata的TCC模式)。
35 6
|
16天前
|
SQL 关系型数据库 MySQL
轻松入门MySQL:保障数据完整性,MySQL事务在进销存管理系统中的应用(12)
轻松入门MySQL:保障数据完整性,MySQL事务在进销存管理系统中的应用(12)
|
23天前
|
关系型数据库 MySQL
elasticsearch对比mysql以及使用工具同步mysql数据全量增量
elasticsearch对比mysql以及使用工具同步mysql数据全量增量
20 0
|
26天前
Mybatis+mysql动态分页查询数据案例——测试类HouseDaoMybatisImplTest)
Mybatis+mysql动态分页查询数据案例——测试类HouseDaoMybatisImplTest)
20 1
|
26天前
Mybatis+mysql动态分页查询数据案例——工具类(MybatisUtil.java)
Mybatis+mysql动态分页查询数据案例——工具类(MybatisUtil.java)
15 1
|
22天前
|
关系型数据库 MySQL
MySQL查询当天昨天明天本月上月今年等数据
MySQL查询当天昨天明天本月上月今年等数据
19 2
|
22天前
|
关系型数据库 MySQL 开发工具
MySQL分组后,组内排序,然后取每组的第一条数据
MySQL分组后,组内排序,然后取每组的第一条数据
15 1
|
23天前
|
canal SQL 关系型数据库
MySQL数据直接实时同步到ES
MySQL数据直接实时同步到ES
32 0
|
26天前
|
Java 数据库连接 mybatis
Mybatis+mysql动态分页查询数据案例——Mybatis的配置文件(mybatis-config.xml)
Mybatis+mysql动态分页查询数据案例——Mybatis的配置文件(mybatis-config.xml)
14 1
|
26天前
Mybatis+mysql动态分页查询数据案例——配置映射文件(HouseDaoMapper.xml)
Mybatis+mysql动态分页查询数据案例——配置映射文件(HouseDaoMapper.xml)
14 1