環境: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
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文檔
隨便寫一些文字,先不考慮有中文。
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)
轉到數據庫,看到插入了一個文本
取出文本,
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)
//不考慮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盤
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相同