jdbc网mysql数据库读取图片

来源:互联网 发布:python iter 编辑:程序博客网 时间:2024/05/16 09:59
blob字段用于存储二进制数据,例如图像、声音、二进制文等。
package utils;import java.io.InputStream;import java.sql.Connection;import java.sql.DriverManager;import java.sql.PreparedStatement;import java.sql.ResultSet;import java.sql.SQLException;import java.util.Properties;public class JdbcUtil {private static String password;private static String username;private static String url;static {try {InputStream in = JdbcUtil.class.getClassLoader().getResourceAsStream("db.properties");Properties pr = new Properties();pr.load(in);username=pr.getProperty("username");url = pr.getProperty("url");password = pr.getProperty("password");String driver = pr.getProperty("driver");Class.forName(driver);} catch (Exception e) {throw new RuntimeException(e);}}public static Connection getConnection() throws SQLException {return DriverManager.getConnection(url, username, password);}public static void release(Connection conn, PreparedStatement st, ResultSet rs) {if(rs!=null){try{rs.close();}catch (Exception e){throw new RuntimeException(e);}rs = null;}if(st != null){try{st.close();}catch (Exception e){throw new RuntimeException(e);}st = null;}if(conn != null){try{conn.close();}catch (Exception e){throw new RuntimeException(e);}conn = null;}}}

package jdbc;import java.io.File;import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.InputStream;import java.sql.Connection;import java.sql.PreparedStatement;import java.sql.ResultSet;import org.junit.Test;import utils.JdbcUtil;public class TestBolb {@Testpublic void add() {Connection conn = null;PreparedStatement st = null;ResultSet rs = null;try {conn = JdbcUtil.getConnection();String sql = "insert into testblob(content) values(?)";st = conn.prepareStatement(sql);//String path = TestClob.class.getClassLoader().getResource("123.jpg").getPath();String path = "d:\\123.jpg";File file = new File(path);st.setBinaryStream(1, new FileInputStream(file), file.length());int num = st.executeUpdate();if (num > 0) {System.out.println("插入成功!!");}} catch (Exception e) {throw new RuntimeException(e);} finally {JdbcUtil.release(conn, st, rs);}}@Testpublic void read(){Connection conn = null;PreparedStatement st = null;ResultSet rs = null;try{conn = JdbcUtil.getConnection();String sql = "select * from testblob where id = 1";st = conn.prepareStatement(sql);rs = st.executeQuery();if (rs.next()) {FileOutputStream out = new FileOutputStream("d:\\1.jpg");InputStream reader = rs.getBinaryStream("content");byte buffer[] = new byte[1024];int len = 0;while ((len = reader.read(buffer)) > 0) {out.write(buffer, 0, len);}out.close();reader.close();}}catch(Exception e){throw new RuntimeException(e);}finally{JdbcUtil.release(conn, st, rs);}}}

0 0
原创粉丝点击