当然应当先建立一个数据库:还是上次的那个
create table picture_db( file_name varchar ( 255) not null , content longblob, primary key ( file_name) ) ;
import java . io . File ; import java . io . FileInputStream ; import java . sql . Connection ; import java . sql . DriverManager ; import java . sql . PreparedStatement ; public class UpImage { protected static Connection dbConnection; protected static String driverName = "com.mysql.jdbc.Driver" ; protected static String dbURL = "jdbc:mysql://localhost:3306/sample_db" ; protected static String userID = "root" ; protected static String passwd = "123" ; protected static String str = "insert into picture_table values(?,?)" ; public static void main( String [ ] args) { try { Class . forName ( driverName) ; dbConnection = DriverManager . getConnection ( dbURL, userID, passwd) ; PreparedStatement pstmt = dbConnection. prepareStatement ( str) ; File f = new File ( "E://pictures-collect//MUST logo.jpg" ) ; FileInputStream fis = new FileInputStream ( f) ; pstmt. setString ( 1, f. getName ( ) ) ; pstmt. setBinaryStream ( 2, fis, ( int ) f. length ( ) ) ; if ( pstmt. executeUpdate ( ) ! = 1) { System . out. print ( "Photo insertion error/n" ) ; } pstmt. close ( ) ; fis. close ( ) ; dbConnection. close ( ) ; } catch ( Exception e) { e. printStackTrace ( ) ; } } }
对照一下,可以不仅从篇幅上减少了很多,而且从内容上看更直接明白。
pstmt. setBinaryStream ( 2, fis, ( int ) f. length ( ) ) ; if ( pstmt. executeUpdate ( ) ! = 1) { System . out. print ( "Photo insertion error/n" ) ; }
短短几句话,就可以把图片转变成二进制码然后存到数据库中。方便直当。
接下来就是如何读取图片了。
import java . io . File ; import java . io . FileOutputStream ; import java . io . InputStream ; import java . sql . * ; public class ShowImage { private static String mySQLDriver = "com.mysql.jdbc.Driver" ; private static String connURL = "jdbc:mysql://localhost:3306/sample_db" ; private static String userName = "root" ; private static String pwd = "123" ; public static Connection conn = null ; private static ResultSet rs = null ; public static void main( String [ ] args) { try { Class . forName ( mySQLDriver) ; conn = DriverManager . getConnection ( connURL, userName, pwd) ; Statement stmt = conn. createStatement ( ) ; rs = stmt . executeQuery ( "select * from picture_table where file_name = 'Logo1'" ) ; if ( rs. next ( ) ) { Blob blob = rs. getBlob ( "content" ) ; InputStream inputStream = blob . getBinaryStream ( ) ; File fileOutput = new File ( "C:clone59dredbookco0ver.jpg" ) ; FileOutputStream fo = new FileOutputStream ( fileOutput) ; int c; while ( ( c = inputStream . read ( ) ) ! = - 1) fo. write ( c) ; fo. close ( ) ; System . out. println ( "Blob reserved" ) ; } } catch ( Exception e) { System . out. println ( e. getMessage ( ) ) ; } } }
简单的笔记:刚开始的时候忘记了写上 if(rs.next(){...}执行的时候一直提是错误:before start of result set!! 我以为是哪个ResultSet出了问题,后来上网查了才知道原来是rs的记录指针在刚开始的时候是在第一条记录之前的,而不是一开始就只在第一条记录上的,所有,得先rs.next();,才行。
上面用 Blob blob = rs.getBlob("content");莱得到二进制文件的内容。然后用I/O流输出成文件到磁盘。这里就不详细介绍,不明白的看看I/O.或者参考