首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 数据库 > 其他数据库 >

用JDBC访问二进制门类的数据

2012-10-29 
用JDBC访问二进制类型的数据用JDBC访问二进制类型的数据?public class BlobTest {public static void main

用JDBC访问二进制类型的数据

用JDBC访问二进制类型的数据

?

public class BlobTest {public static void main(String[] args) throws SQLException, IOException, ClassNotFoundException {// create();read();}// 从数据库读取二进制类型的数据static void read() throws SQLException, IOException, ClassNotFoundException {Connection conn = null;PreparedStatement ps = null;ResultSet rs = null;try {// 1.加载驱动Class.forName("com.mysql.jdbc.Driver");// 2.建立连接conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/jdbc", "root", "123456");// 3.创建语句ps = conn.prepareStatement("select big_bit from blob_test");// 4.执行语句rs = ps.executeQuery();// 5.处理结果while (rs.next()) {Blob blob = rs.getBlob(1);InputStream in = blob.getBinaryStream();File file = new File("IMG_0002_bak.jpg");OutputStream out =  new BufferedOutputStream(new FileOutputStream(file));byte[] buff = new byte[1024];for (int i = 0; (i = in.read(buff)) > 0;) {out.write(buff, 0, i);}out.close();in.close();}} finally {if (rs != null)rs.close(); rs = null;if (ps != null)ps.close();ps = null;if (conn != null) conn.close();conn = null;}}// 把二进制类型的数据(这里是一张图片)存入数据库static void create() throws SQLException, IOException, ClassNotFoundException {Connection conn = null;PreparedStatement ps = null;ResultSet rs = null;try {// 1.加载驱动Class.forName("com.mysql.jdbc.Driver");// 2.建立连接conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/jdbc", "root", "123456");// 3.创建语句String sql = "insert into blob_test(big_bit) values (?)";ps = conn.prepareStatement(sql);File file = new File("IMG_0002.jpg");InputStream in = new BufferedInputStream(new FileInputStream(file));ps.setBinaryStream(1, in, (int) file.length());// 4.执行语句int i = ps.executeUpdate();in.close();System.out.println("i=" + i);} finally {if (rs != null)rs.close(); rs = null;if (ps != null)ps.close();ps = null;if (conn != null) conn.close();conn = null;}}}

?

热点排行