JDBC操作MySQL Lob字段记实

本文涉及的产品
RDS MySQL Serverless 基础系列,0.5-2RCU 50GB
No entry or manifest in @ali/alfa-aliyundotcom-free-widget-goods-card
Error: No entry or manifest in @ali/alfa-aliyundotcom-free-widget-goods-card
    at https://g.alicdn.com/aliyun/developer-aliyun-com-fe/2.8.49/scripts/articleDetail.js:1:578343
    at h (https://g.alicdn.com/aliyun/developer-aliyun-com-fe/2.8.49/scripts/articleDetail.js:1:379364)
    at Generator.<anonymous> (https://g.alicdn.com/aliyun/developer-aliyun-com-fe/2.8.49/scripts/articleDetail.js:1:380687)
    at Generator.next (https://g.alicdn.com/aliyun/developer-aliyun-com-fe/2.8.49/scripts/articleDetail.js:1:379774)
    at Pe (https://g.alicdn.com/aliyun/developer-aliyun-com-fe/2.8.49/scripts/articleDetail.js:1:491844)
    at a (https://g.alicdn.com/aliyun/developer-aliyun-com-fe/2.8.49/scripts/articleDetail.js:1:492048)
    at https://g.alicdn.com/aliyun/developer-aliyun-com-fe/2.8.49/scripts/articleDetail.js:1:492109
    at new Promise (<anonymous>)
    at https://g.alicdn.com/aliyun/developer-aliyun-com-fe/2.8.49/scripts/articleDetail.js:1:491988
    at https://g.alicdn.com/aliyun/developer-aliyun-com-fe/2.8.49/scripts/articleDetail.js:1:578533
云数据库 RDS MySQL,集群系列 2核4GB
推荐场景:
搭建个人博客
No entry or manifest in @ali/alfa-aliyundotcom-free-widget-goods-card
Error: No entry or manifest in @ali/alfa-aliyundotcom-free-widget-goods-card
    at https://g.alicdn.com/aliyun/developer-aliyun-com-fe/2.8.49/scripts/articleDetail.js:1:578343
    at h (https://g.alicdn.com/aliyun/developer-aliyun-com-fe/2.8.49/scripts/articleDetail.js:1:379364)
    at Generator.<anonymous> (https://g.alicdn.com/aliyun/developer-aliyun-com-fe/2.8.49/scripts/articleDetail.js:1:380687)
    at Generator.next (https://g.alicdn.com/aliyun/developer-aliyun-com-fe/2.8.49/scripts/articleDetail.js:1:379774)
    at Pe (https://g.alicdn.com/aliyun/developer-aliyun-com-fe/2.8.49/scripts/articleDetail.js:1:491844)
    at a (https://g.alicdn.com/aliyun/developer-aliyun-com-fe/2.8.49/scripts/articleDetail.js:1:492048)
    at https://g.alicdn.com/aliyun/developer-aliyun-com-fe/2.8.49/scripts/articleDetail.js:1:492109
    at new Promise (<anonymous>)
    at https://g.alicdn.com/aliyun/developer-aliyun-com-fe/2.8.49/scripts/articleDetail.js:1:491988
    at https://g.alicdn.com/aliyun/developer-aliyun-com-fe/2.8.49/scripts/articleDetail.js:1:578533
RDS MySQL Serverless 高可用系列,价值2615元额度,1个月
No entry or manifest in @ali/alfa-aliyundotcom-free-widget-goods-card
Error: No entry or manifest in @ali/alfa-aliyundotcom-free-widget-goods-card
    at https://g.alicdn.com/aliyun/developer-aliyun-com-fe/2.8.49/scripts/articleDetail.js:1:578343
    at h (https://g.alicdn.com/aliyun/developer-aliyun-com-fe/2.8.49/scripts/articleDetail.js:1:379364)
    at Generator.<anonymous> (https://g.alicdn.com/aliyun/developer-aliyun-com-fe/2.8.49/scripts/articleDetail.js:1:380687)
    at Generator.next (https://g.alicdn.com/aliyun/developer-aliyun-com-fe/2.8.49/scripts/articleDetail.js:1:379774)
    at Pe (https://g.alicdn.com/aliyun/developer-aliyun-com-fe/2.8.49/scripts/articleDetail.js:1:491844)
    at a (https://g.alicdn.com/aliyun/developer-aliyun-com-fe/2.8.49/scripts/articleDetail.js:1:492048)
    at https://g.alicdn.com/aliyun/developer-aliyun-com-fe/2.8.49/scripts/articleDetail.js:1:492109
    at new Promise (<anonymous>)
    at https://g.alicdn.com/aliyun/developer-aliyun-com-fe/2.8.49/scripts/articleDetail.js:1:491988
    at https://g.alicdn.com/aliyun/developer-aliyun-com-fe/2.8.49/scripts/articleDetail.js:1:578533
简介:
JDBC操作MySQL Lob字段记实
 
虽然Java的持久化框架多如牛毛,但都离不开JDBC技术,JDBC在某些时候是其他框架难以取代的。也是java操作数据库最根本的技术。
 
上文写了JDBC操作DB2 Lob字段bug问题,为此,我还特意写了MySQL平台下的Lob字段操作,以便能得出更为准确的结论。
 
本文通过一个简单的Java类,就能增删改查MySQL的Lob字段。google一下,JDBC操作数据库Lob字段的完整代码一个也没找到。因此把这个测试代码也放在blog上,希望给正在用JDBC做MySQL开发的朋友们一点参考。
 
环境:
MySQL-5.0.45
mysql-connector-java-5.1.5.zip
 
测试的SQL脚本:
CREATE  TABLE t_lob ( 
   NAME  varchar(24)  DEFAULT  NULL
  TXT  text
  IMG blob 
) ENGINE=InnoDB  DEFAULT CHARSET=gbk;
 
测试代码:
package lob; 

import java.sql.*; 
import java.io.*; 

/** 
* JDBC 读取MySQL lob字段测试 
* File: TestLob4MySQL.java 
* User: leizhimin 
* Date: 2008-3-3 14:44:30 
*/
 
public  class TestLob4MySQL { 
     public  static  final String url =  "jdbc:mysql://localhost/testdb"; 
    public static final String username = "root"
    public static final String password = "leizhimin"
    public static final String driverClassName = "com.mysql.jdbc.Driver"


    /** 
     * 数据库连接获取器 
     * 
     * @return 数据库连接 
     */
 
    public static Connection makeConnection() { 
        Connection conn = null
        try { 
            Class.forName(driverClassName); 
        } catch (ClassNotFoundException e) { 
            e.printStackTrace(); 
        } 
        try { 
            conn = DriverManager.getConnection(url, username, password); 
        } catch (SQLException e) { 
            e.printStackTrace(); 
        } 
        return conn; 
    } 

    /** 
     * 测试数据库连接 
     */
 
    public static void testConnection() { 
        Connection conn = makeConnection(); 
        try { 
            Statement stmt = conn.createStatement(); 
            ResultSet rs = stmt.executeQuery("SELECT * FROM mysql.user"); 
            while (rs.next()) { 
                String s1 = rs.getString(1); 
                System.out.println(s1); 
            } 
            rs.close(); 
            stmt.close(); 
        } catch (SQLException e) { 
            e.printStackTrace(); 
        } finally { 
            try { 
                conn.close(); 
            } catch (SQLException e) { 
                e.printStackTrace(); 
            } 
        } 
    } 

    /** 
     * 插入Lob字段 
     */
 
    public static void testInsertlob() { 
        Connection conn = makeConnection(); 
        try { 
            conn.setAutoCommit(false); 
            File txtFile = new File("C:\\txt.txt"); 
            File imgFile = new File("C:\\img.png"); 
            int txt_len = (int) txtFile.length(); 
            int img_len = (int) imgFile.length(); 
            try { 
                InputStream fis1 = new FileInputStream(txtFile); 
                InputStream fis2 = new FileInputStream(imgFile); 
                PreparedStatement pstmt = conn.prepareStatement("INSERT INTO T_LOB(NAME,TXT,IMG) VALUES('G',?,?)"); 
                pstmt.setAsciiStream(1, fis1, txt_len); 
                pstmt.setBinaryStream(2, fis2, img_len); 
                pstmt.executeUpdate(); 
                conn.commit(); 
            } catch (FileNotFoundException e) { 
                e.printStackTrace(); 
            } 
        } catch (SQLException e) { 
            e.printStackTrace(); 
        } finally { 
            try { 
                conn.close(); 
            } catch (SQLException e) { 
                e.printStackTrace(); 
            } 
        } 
    } 

    /** 
     * 读取lob字段 
     */
 
    public static void testQueryLob() { 
        Connection conn = makeConnection(); 
        try { 
            conn.setAutoCommit(false); 
            Statement stmt = conn.createStatement(); 
            ResultSet rs = stmt.executeQuery("SELECT TXT,IMG FROM T_LOB"); 
            int i = 1; 
            while (rs.next()) { 
                Clob clob = rs.getClob("TXT"); 
                Blob blob = rs.getBlob("IMG"); 
                InputStream txtIs = rs.getAsciiStream("TXT"); 
                InputStream imgIs = rs.getBinaryStream("IMG"); 

                InputStreamReader txtIsr = new InputStreamReader(txtIs); 
                InputStreamReader imgIsr = new InputStreamReader(imgIs); 

                BufferedReader buff_txtIsr = new BufferedReader(txtIsr); 
                BufferedReader buff_imgIsr = new BufferedReader(imgIsr); 

                String line = null
                while (null != (line = buff_txtIsr.readLine())) { 
                    System.out.println(line); //将其输出至屏幕,实际你可以按照需要处理 
                } 

                File fileOutput = new File("c:\\img_x" + i + ".png"); 
                FileOutputStream fo = new FileOutputStream(fileOutput); 
                int c; 
                while ((c = imgIs.read()) != -1) 
                    fo.write(c); 
                fo.close(); 
                System.out.println("img " + i + " retrieved!"); 
                i++; 
            } 
            conn.commit(); 
        } catch (SQLException e) { 
            e.printStackTrace(); 
        } catch (Exception e) { 
            e.printStackTrace(); 
        } finally { 
            try { 
                conn.close(); 
            } catch (SQLException e) { 
                e.printStackTrace(); 
            } 
        } 

    } 

    /** 
     * 读取lob字段 
     */
 
    public static void testQueryLob1() { 
        Connection conn = makeConnection(); 
        try { 
            conn.setAutoCommit(false); 
            Statement stmt = conn.createStatement(); 
            ResultSet rs = stmt.executeQuery("SELECT TXT,IMG FROM T_LOB"); 
            while (rs.next()) { 
                Clob clob = rs.getClob("TXT"); 
                Blob blob = rs.getBlob("IMG"); 
                InputStream txtIs = clob.getAsciiStream(); 
                InputStream imgIs = blob.getBinaryStream(); 

                InputStreamReader txtIsr = new InputStreamReader(txtIs); 
                InputStreamReader imgIsr = new InputStreamReader(imgIs); 

                BufferedReader buff_txtIsr = new BufferedReader(txtIsr); 
                BufferedReader buff_imgIsr = new BufferedReader(imgIsr); 

                String line = null
                while (null != (line = buff_txtIsr.readLine())) { 
                    System.out.println(line); //将其输出至屏幕,实际你可以按照需要处理 
                } 
            } 
            conn.commit(); 
        } catch (SQLException e) { 
            e.printStackTrace(); 
        } catch (Exception e) { 
            e.printStackTrace(); 
        } finally { 
            try { 
                conn.close(); 
            } catch (SQLException e) { 
                e.printStackTrace(); 
            } 
        } 
    } 

    /** 
     * 删除lob字段 
     */
 
    public static void testDeleteLob() { 
        Connection conn = makeConnection(); 
        try { 
            conn.setAutoCommit(false); 
            Statement stmt = conn.createStatement(); 
            int row = stmt.executeUpdate("DELETE FROM T_LOB"); 
            conn.commit(); 
            System.out.println("删除 " + row + " 行数据!"); 
        } catch (SQLException e) { 
            e.printStackTrace(); 
        } finally { 
            try { 
                conn.close(); 
            } catch (SQLException e) { 
                e.printStackTrace(); 
            } 
        } 
    } 

    /** 
     * 读取lob字段 
     */
 
    public static void testUpdateLob() { 
        Connection conn = makeConnection(); 

        try { 
            String in_str="HAHAHAHAHAHA!!!"
            File in_file=new File("c:\\img_haha.png"); 
            InputStream txt_is = string2InputStream(in_str); 
            InputStream img_is =new FileInputStream(in_file); 

            conn.setAutoCommit(false); 
            PreparedStatement pstmt = conn.prepareStatement("UPDATE T_LOB SET TXT=?, IMG=? WHERE NAME='G'"); 
            pstmt.setAsciiStream(1,txt_is,in_str.getBytes().length); 
            pstmt.setBinaryStream(2,img_is,(int)in_file.length()); 

            int row = pstmt.executeUpdate(); 

            conn.commit(); 
            txt_is.close(); 
            img_is.close(); 

//            System.out.println("更新 " + row + " 行数据!"); 
        } catch (SQLException e) { 
            e.printStackTrace(); 
        } catch (FileNotFoundException e) { 
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates. 
        } catch (IOException e) { 
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates. 
        } finally { 
            try { 
                conn.close(); 
            } catch (SQLException e) { 
                e.printStackTrace(); 
            } 
        } 
    } 

    public static void main(String args[]) { 
//        testInsertlob(); 
//        testQueryLob(); 
//        testQueryLob1(); 
//        testDeleteLob(); 
        testUpdateLob(); 
    } 

    public static InputStream string2InputStream(String str) { 
        if (str == nullreturn null
        return new ByteArrayInputStream(str.getBytes()); 
    } 

    public static String inputStream2String(InputStream is) { 
        StringBuffer sb = new StringBuffer(); 
        BufferedReader br = new BufferedReader(new InputStreamReader(is)); 
        String inputLine; 
        try { 
            while ((inputLine = br.readLine()) != null) { 
                sb.append(inputLine).append("\n"); 
            } 
        } catch (IOException e) { 
            e.printStackTrace(); 
        } 
        return sb.toString(); 
    } 
}
 
一一运行各个测试方法,都没有问题。


本文转自 leizhimin 51CTO博客,原文链接:http://blog.51cto.com/lavasoft/64963,如需转载请自行联系原作者
相关实践学习
如何快速连接云数据库RDS MySQL
本场景介绍如何通过阿里云数据管理服务DMS快速连接云数据库RDS MySQL,然后进行数据表的CRUD操作。
全面了解阿里云能为你做什么
阿里云在全球各地部署高效节能的绿色数据中心,利用清洁计算为万物互联的新世界提供源源不断的能源动力,目前开服的区域包括中国(华北、华东、华南、香港)、新加坡、美国(美东、美西)、欧洲、中东、澳大利亚、日本。目前阿里云的产品涵盖弹性计算、数据库、存储与CDN、分析与搜索、云通信、网络、管理与监控、应用服务、互联网中间件、移动服务、视频服务等。通过本课程,来了解阿里云能够为你的业务带来哪些帮助 &nbsp; &nbsp; 相关的阿里云产品:云服务器ECS 云服务器 ECS(Elastic Compute Service)是一种弹性可伸缩的计算服务,助您降低 IT 成本,提升运维效率,使您更专注于核心业务创新。产品详情: https://www.aliyun.com/product/ecs
目录
打赏
0
0
0
0
265
分享
相关文章
【YashanDB 知识库】JDBC 驱动的 date 类型字段结果集调用 getString 方法只返回日期,不返回时分秒
**问题简介:** 在使用 JDBC 驱动查询 YashanDB 的 date 类型字段时,直接调用 ResultSet 的 getString 方法仅返回 YYYY-MM-DD 格式的日期字符串,缺少时分秒信息,影响业务逻辑。此问题存在于所有 YashanDB 驱动版本,原因是驱动内部实现问题。解决方法包括使用 `rs.getTimestamp(1).toString()` 或在 JDBC 连接串中添加 `mapDateToTimestamp=true` 参数。 **风险及影响:** 返回的字符串只有日期部分,缺失时间信息,可能导致业务逻辑异常。
【YashanDB 知识库】JDBC 驱动的 date 类型字段结果集调用 getString 方法只返回日期,不返回时分秒
**问题简介:** 在使用 JDBC 驱动查询 YashanDB 中的 date 类型字段时,直接调用 ResultSet 的 getString 方法仅返回日期部分(YYYY-MM-DD),缺少时分秒信息,影响业务逻辑。此问题存在于所有 YashanDB 驱动版本,原因是驱动内部实现问题。解决方法:使用 `rs.getTimestamp(1).toString()` 或在连接串中增加 `mapDateToTimestamp=true` 参数。 **风险及影响:** 返回字符串缺少时分秒,可能导致业务逻辑错误。 **受影响版本:** 所有 YashanDB 驱动版本。
MySQL的group by与count(), *字段使用问题
正确使用 `GROUP BY`和 `COUNT()`函数是进行数据聚合查询的基础。通过理解它们的用法和常见问题,可以有效避免查询错误和性能问题。无论是在单列分组、多列分组还是结合其他聚合函数的场景中,掌握这些技巧和注意事项都能大大提升数据查询和分析的效率。
453 0
SpringBoot项目中mysql字段映射使用JSONObject和JSONArray类型
SpringBoot项目中mysql字段映射使用JSONObject和JSONArray类型 图像处理 光通信 分布式计算 算法语言 信息技术 计算机应用
91 8
SpringBoot项目中mysql字段映射使用JSONObject和JSONArray类型
SpringBoot项目中mysql字段映射使用JSONObject和JSONArray类型
96 0
mysql5.7 jdbc驱动
遵循上述步骤,即可在Java项目中高效地集成MySQL 5.7 JDBC驱动,实现数据库的访问与管理。
1025 1
MySQL新增字段/索引会不会锁表?
MySQL新增字段/索引会不会锁表?
492 0
Hadoop-24 Sqoop迁移 MySQL到Hive 与 Hive到MySQL SQL生成数据 HDFS集群 Sqoop import jdbc ETL MapReduce
Hadoop-24 Sqoop迁移 MySQL到Hive 与 Hive到MySQL SQL生成数据 HDFS集群 Sqoop import jdbc ETL MapReduce
185 0
Hadoop-23 Sqoop 数据MySQL到HDFS(部分) SQL生成数据 HDFS集群 Sqoop import jdbc ETL MapReduce
Hadoop-23 Sqoop 数据MySQL到HDFS(部分) SQL生成数据 HDFS集群 Sqoop import jdbc ETL MapReduce
76 0
Hadoop-22 Sqoop 数据MySQL到HDFS(全量) SQL生成数据 HDFS集群 Sqoop import jdbc ETL MapReduce
Hadoop-22 Sqoop 数据MySQL到HDFS(全量) SQL生成数据 HDFS集群 Sqoop import jdbc ETL MapReduce
113 0