环境:MySql+SQLyog+j2se+jdbc
存储文本用longtext类型
存储图片用blob类型
1、首先建表
create table t_t (
id int(16) NOT NULL AUTO_INCREMENT,
longText longtext,
picture blob,
PRIMARY KEY (`id`)
) ;
`longText` longtext,//文本txt
`picture` blob,//图片pic
数据库为t_test,表为t_t
2、jdbc操作,打开eclipse for j2se
1 2 3 4 5 6 7 8 9 10 | String jdbcName= "com.mysql.jdbc.Driver" ; String dbUrl= "jdbc:mysql://localhost:3306/t_test" ; String dbUserName= "root" ; String dbPassword= "123456" ; Class.forName(jdbcName); //加载驱动 Connection conn=DriverManager.getConnection(dbUrl,dbUserName,dbPassword); //连接 //构造第一个SQL语句,先不管图片,先插入文本 String sql= "insert into t_t values(NUll,?,NULL)" ; //?为第一个坑 PreparedStatement pst=conn.prepareStatement(sql); |
找材料:
在E盘建立两个TXT文档
随便写一些文字,先不考虑有中文。
1 2 3 4 5 6 7 8 9 10 11 | File context= new File( "e:/h01.txt" ); //File文件 InputStream inputStream= new FileInputStream(context); //使用流 pst.setAsciiStream( 1 ,inputStream,context.length()); //填第一个坑 int result=pst.executeUpdate(); //执行SQL语句 if (result== 1 ){ //提示信息 System.out.println( "插入成功" ); } else { System.out.println( "插入失败" ); } |
有一些异常用 throws抛出(throws ClassNotFoundException, SQLException, FileNotFoundException)
转到数据库,看到插入了一个文本
取出文本,
1 2 3 4 5 6 7 8 9 | String sql= "select * from t_t where id=?" ; //挖坑? PreparedStatement pst=conn.prepareStatement(sql); pst.setInt( 1 , 1 ); //第一个1是填第一个坑,第二个1是数据库中id为1的记录 ResultSet rs=pst.executeQuery(); if (rs.next()){ Clob c=rs.getClob( "longText" ); //使用Clob String str=c.getSubString( 1 , ( int )c.length()); //赋值给字符串 System.out.println(str); //输出文本 } |
运行如下:
结果与h01.txt的结果一致
图片picture的存储
在E盘准备一张图片(002.jpg)
1 2 3 4 5 6 7 8 9 10 11 12 | //不考虑txt(设置为NULL)只考虑jpg String sql= "insert into t_t values(NUll,NULL,?)" ; //挖坑 PreparedStatement pst=conn.prepareStatement(sql); File pic= new File( "e:/002.jpg" ); InputStream inputStream= new FileInputStream(pic); pst.setBinaryStream( 1 , inputStream,pic.length()); //填坑 int result=pst.executeUpdate(); if (result== 1 ){ //提示信息 System.out.println( "插入成功" ); } else { System.out.println( "插入失败" ); } |
eclipse插入成功,看数据库。
002.jpg已经插入到了数据库
下一步
取出图片到F盘
1 2 3 4 5 6 7 8 9 10 11 12 13 | String sql= "select picture from t_t where id=?" ; //挖坑 PreparedStatement pst=conn.prepareStatement(sql); pst.setInt( 1 , 2 ); //填坑,2表示数据库的id=2的这条记录 ResultSet rs=pst.executeQuery(); if (rs.next()){ Blob b=rs.getBlob( "picture" ); //输出到F盘并且命名为003.jpg FileOutputStream out= new FileOutputStream( new File( "f:/003.jpg" )); out.write(b.getBytes( 1 , ( int )b.length())); out.close(); } conn.close(); |
运行成功,F盘多了一个003.jpg与002.jpg相同