做一個(gè)將本地圖片上傳到mysql數(shù)據(jù)庫(kù)的小實(shí)例,順便也下載下來到桌面檢測(cè)是否上傳成功。
在寫代碼之前得先在數(shù)據(jù)庫(kù)中建立image表,用來存儲(chǔ)圖片。
create table image (id int primary key auto_increment , name varchar(30) COMMENT '名稱', content mediumblob COMMENT '圖片');
下面直接上代碼:
package jdbc_imagetest;import java.io.*;import java.sql.*;/** * 將本地文件的圖片傳到數(shù)據(jù)庫(kù)的test的image表中并下載到本機(jī)桌面 */public class Test1 { private static String url="jdbc:mysql://localhost:3306/test"; private static String user="root"; private static String password="123456"; private static Connection con; public static void main(String[] args) throws Exception { Class.forName("com.mysql.jdbc.Driver"); con=DriverManager.getConnection(url,user,password); shangchuan(); xiazai(); } //添加圖片到數(shù)據(jù)庫(kù)test4的file表 public static void shangchuan() throws Exception{ String sql="insert into image(name,content) values(?,?)"; PreparedStatement ptmt=con.prepareStatement(sql); ptmt.setString(1, "美女.jpg"); InputStream is=null; is=new FileInputStream("D://Pictures//3.jpg"); ptmt.setBinaryStream(2, is,is.available()); //方法說明:PreparedStatement.setBinaryStream(int parameterIndex, InputStream x, int length) ptmt.execute(); System.out.println("圖片添加成功!"); } //從數(shù)據(jù)庫(kù)中把圖片下載至桌面 public static void xiazai() throws Exception{ String sql="select content from image where id=3";//在我這里3.jpg是第三張圖片 Statement stmt=con.createStatement(); ResultSet rs=stmt.executeQuery(sql);//將查詢結(jié)果給rs if(rs.next()){ InputStream is=rs.getBinaryStream("fcontent"); //.getBinaryStream():a Java input stream that delivers the database column value as a stream of uninterpreted bytes FileOutputStream fos=new FileOutputStream("C://Users//Desktop//美女.jpg"); byte[] buffer=new byte[1024]; int len=0; while((len=is.read(buffer))!=-1){ fos.write(buffer,0,len);//將數(shù)據(jù)庫(kù)的圖片寫出 } System.out.println("下載成功!已下載至桌面,請(qǐng)查看"); }else{ System.out.println("圖片不存在!"); } con.close(); }}測(cè)試成功
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持武林網(wǎng)。
新聞熱點(diǎn)
疑難解答
圖片精選