JDBC 使用 mysql Blob类型

来源:互联网 发布:vue.js 兼容性问题 编辑:程序博客网 时间:2024/05/23 20:40
package com.zf.test;import java.awt.Graphics;import java.awt.image.BufferedImage;import java.io.File;import java.io.FileInputStream;import java.sql.Blob;import java.sql.Connection;import java.sql.DriverManager;import java.sql.PreparedStatement;import java.sql.ResultSet;import java.sql.SQLException;import javax.imageio.ImageIO;import javax.swing.JFrame;import org.apache.commons.io.IOUtils;public class JDBCTest {private final String url = "jdbc:mysql:///ssh";private final String driverClass = "com.mysql.jdbc.Driver";private final String username  = "zf";private final String password = "0";{try {Class.forName(driverClass);   } catch (ClassNotFoundException e) {e.printStackTrace();} }/* 获取连接 */public Connection openConnection(){try {return DriverManager.getConnection(url, username , password);} catch (SQLException e) {e.printStackTrace();return null ;}}/*创建表*/public void createTable(){try {Connection conn = openConnection();boolean delete = conn.prepareStatement("drop table if exists tab").execute();System.out.println(delete ? "删除tab 失败" : "删除tab成功");PreparedStatement ps =conn.prepareStatement  ("CREATE TABLE `tab` (`id`  integer NULL AUTO_INCREMENT ,`file`  blob NULL ,`img`  blob NULL ,PRIMARY KEY (`id`))");boolean result = ps.execute();System.out.println(result ? "创建tab失败" : "创建tab成功");ps.close();  conn.close();} catch (SQLException e) {e.printStackTrace();  }}/*插入一条记录*/public void insertTotab(){try {Connection conn = openConnection();PreparedStatement ps =conn.prepareStatement("insert into tab(file , img) values(? , ?)");//设置类型为Blobps.setBlob(1, new FileInputStream(new File("c:/xxx.txt")));ps.setBlob(2 , new FileInputStream(new File("C:/logo.gif")) );int i = ps.executeUpdate();  System.out.println(i > 0 ? "保存成功" : "保存失败");ps.close();conn.close();} catch (Exception e) {e.printStackTrace();}}/* 读取内容 */public void readContent(){try {Connection conn = openConnection();PreparedStatement ps =conn.prepareStatement("select * from tab");ResultSet rs = ps.executeQuery();if(rs.next()){Blob file = rs.getBlob(2);Blob img = rs.getBlob(3);System.out.println("------------file-----------");//读取文件流System.out.println(IOUtils.toString(file.getBinaryStream()));//读取图片流BufferedImage bi = ImageIO.read(img.getBinaryStream());//将图片流转换为图片显示出来showImg(bi); System.out.println("读取成功");}rs.close();ps.close();  conn.close();} catch (Exception e) {e.printStackTrace();}}/* 使用JFrame显示图片 */public void showImg(final BufferedImage bi ){JFrame frame = new JFrame("图片测试"){@Overridepublic void paint(Graphics g) {super.paint(g);g.drawImage(bi, 50 , 50 , null );}  };frame.setVisible(true);frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);frame.setBounds(0, 0, 500, 500);}public static void main(String[] args) {JDBCTest jt = new JDBCTest();jt.createTable();jt.insertTotab();jt.readContent();}}

原创粉丝点击