JDBC操作MySQL Lob字段记实

news/2024/7/5 3:22:03
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,如需转载请自行联系原作者

http://lihuaxi.xjx100.cn/news/238516.html

相关文章

Kali Linux攻防系统(三:在Kali Linux系统中配置安全测试浏览器及系统清理备份)

任务三:配置安全测试浏览器及系统清理备份 3.1、汉化Firefox并安装安全插件 3.1.1、汉化Firefox浏览器,安装中文插件,并更改设置; 3.1.2、在浏览器附加组件管理器中查找“Web Developr”插件 3.1.3、安装添加附件组件 3.2、手动…

程序员真的会穷途末路吗?牵引力教育资深大佬这样说

随着互联网IT行业不断的迅速发展,软件开发行业中,往往透露这很多疑问,年龄歧视、职业的转向等方面。牵引力教育资深大佬带你了解职业规划会有哪些方向? 一、技术方向 架构师,系统分析师,是CTO这种往往是走纯技术路线, …

待办事项优先级 开发_如何通过创建主题待办事项确定学习内容的优先级

待办事项优先级 开发by Dan Draper通过丹德雷珀(Dan Draper) 如何通过创建主题待办事项确定学习内容的优先级 (How to prioritize what you learn by creating a topic backlog) 25年编码经验 (Lessons from 25 years of coding) Way back in 1994, I started learning how to…

原生ajax+php上传图片的简单实现

前端 <input type"file" onclick"updown" accept"image/png,image/gif">//accept限制上传的类型<script> function upload1(obj){ var files obj.files ; var formData new FormData();$.ajax({url: download.php,type: "POS…

Nmap安装和扫描(一:Nmap安装和扫描基础知识点总结)

实验目的及要求 完成VMware Workstations14平台安装&#xff0c;会应用相关操作&#xff1b;完成Windows 7操作系统及Kali Linux操作系统的安装&#xff1b;掌握安全扫描的概念、意义及应用分析&#xff1b;掌握Nmap扫描器的安装&#xff1b;针对特定扫描目的&#xff0c;掌握…

以太坊交易事件,日志的理解是什么,详细解析

想知道更多区块链技术知识&#xff0c;请百度【链客区块链技术问答社区】 链客&#xff0c;有问必答&#xff01;&#xff01;Ethereum transation event and log 以太坊交易事件的功能有三个&#xff1a; 用于返回智能合约执行过程中的返回值到用户界面同步触发前端用户界面事…

入职体检体检错了_我们如何更新入职体验并获得更多用户

入职体检体检错了by William Woodhead威廉伍德黑德(William Woodhead) 我们如何更新入职体验并获得更多用户 (How we updated our onboarding experience and got more users) 我们过去将转化率提高60&#xff05;的方法 (Methods we used to increase conversion by 60%) As …

整理下.net分布式系统架构的思路

最近看到有部分招聘信息&#xff0c;要求应聘者说一下分布式系统架构的思路。今天早晨正好有些时间&#xff0c;我也把我们实际在.net方面网站架构的演化路线整理一下&#xff0c;只是我自己的一些想法&#xff0c;欢迎大家批评指正。 首先说明的是.net下开源内容较少&#xff…