MySQL存儲文本和圖片的方法
發(fā)布日期:2022-03-14 16:24 | 文章來源:站長之家
Oracle中大文本數(shù)據(jù)類型
Clob 長文本類型 (MySQL中不支持,使用的是text) Blob 二進(jìn)制類型
MySQL數(shù)據(jù)庫
Text 長文本類型 TINYTEXT: 256 bytes TEXT: 65,535 bytes => ~64kb MEDIUMTEXT: 16,777,215 bytes => ~16MB LONGTEXT: 4,294,967,295 bytes => ~4GB Blob 二進(jìn)制類型
例如:
建表
CREATE TABLE test( id INT PRIMARY KEY AUTO_INCREMENT, content LONGTEXT, -- 文本字段 img LONGBLOB -- 圖片字段 );
存儲文本時是以字符類型存儲,存儲圖片時是以二進(jìn)制類型存儲,具體使用的設(shè)置參數(shù)方法,和獲取數(shù)據(jù)方法不同。
例如:
// 存儲文本時
// 存儲時,設(shè)置參數(shù)為字符流 FileReader reader
pstmt.setCharacterStream(1, reader);
// 獲取參數(shù)時
// 方式1:
Reader r = rs.getCharacterStream("conte
/**
* 保存照片
*
*/
@Test
public void test2(){
String sql = "insert into test(img) values(?)";
try{
con = JDBCUtil.getConnection();
pstmt = con.prepareStatement(sql);
// 設(shè)置參數(shù)
// 獲取文本
File file = new File("f:/a.jpg");
InputStream in = new FileInputStream(file);
// 設(shè)置參數(shù)為2進(jìn)制流
pstmt.setBinaryStream(1, in);
// 執(zhí)行sql
pstmt.executeUpdate();
in.close();
}catch (Exception e) {
e.printStackTrace();
}finally{
try {
JDBCUtil.close(con, pstmt);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
/**
* 獲取照片
*
*/
@Test
public void test3(){
String sql = "select * from test where id=?;";
try{
con = JDBCUtil.getConnection();
pstmt = con.prepareStatement(sql);
// 設(shè)置參數(shù)
pstmt.setInt(1, 2);
// 執(zhí)行查詢
rs = pstmt.executeQuery();
while(rs.next()){
byte[] buff = new byte[1024];
InputStream in = rs.getAsciiStream("img");
int l=0;
OutputStream out = new FileOutputStream(new File("f:/1.jpg"));
while((l=in.read(buff))!=-1){
out.write(buff, 0, l);
}
in.close();
out.close();
}
}catch (Exception e) {
e.printStackTrace();
}finally{
try {
JDBCUtil.close(con, pstmt);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
總結(jié)
以上就是這篇文章的全部內(nèi)容了,希望本文的內(nèi)容對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,謝謝大家對本站的支持。如果你想了解更多相關(guān)內(nèi)容請查看下面相關(guān)鏈接
版權(quán)聲明:本站文章來源標(biāo)注為YINGSOO的內(nèi)容版權(quán)均為本站所有,歡迎引用、轉(zhuǎn)載,請保持原文完整并注明來源及原文鏈接。禁止復(fù)制或仿造本網(wǎng)站,禁止在非maisonbaluchon.cn所屬的服務(wù)器上建立鏡像,否則將依法追究法律責(zé)任。本站部分內(nèi)容來源于網(wǎng)友推薦、互聯(lián)網(wǎng)收集整理而來,僅供學(xué)習(xí)參考,不代表本站立場,如有內(nèi)容涉嫌侵權(quán),請聯(lián)系alex-e#qq.com處理。
相關(guān)文章
關(guān)注官方微信