共計 1968 個字符,預計需要花費 5 分鐘才能閱讀完成。
自動寫代碼機器人,免費開通
本篇文章為大家展示了怎么在 MySQL 中存儲文本和圖片,內容簡明扼要并且容易理解,絕對能使你眼前一亮,通過這篇文章的詳細介紹希望你能有所收獲。
Oracle 中大文本數據類型
Clob 長文本類型 (MySQL 中不支持,使用的是 text)Blob 二進制類型
MySQL 數據庫
Text 長文本類型
TINYTEXT: 256 bytes
TEXT: 65,535 bytes = ~64kb
MEDIUMTEXT: 16,777,215 bytes = ~16MB
LONGTEXT: 4,294,967,295 bytes = ~4GB
Blob 二進制類型
例如:
建表
CREATE TABLE test(
id INT PRIMARY KEY AUTO_INCREMENT,
content LONGTEXT, -- 文本字段
img LONGBLOB -- 圖片字段
);
存儲文本時是以字符類型存儲,存儲圖片時是以二進制類型存儲,具體使用的設置參數方法,和獲取數據方法不同。
例如:
// 存儲文本時
// 存儲時,設置參數為字符流 FileReader reader
pstmt.setCharacterStream(1, reader);
// 獲取參數時
// 方式 1:
Reader r = rs.getCharacterStream( content
// 獲取長文本數據, 方式 2:
System.out.print(rs.getString( content));
// 存儲二進制圖片時
// 設置參數為 2 進制流 InputStream in
pstmt.setBinaryStream(1, in);
// 獲取 2 進制流
InputStream in = rs.getAsciiStream(img
/**
* 保存照片
*
*/
@Test
public void test2(){ String sql = insert into test(img) values(?)
try{ con = JDBCUtil.getConnection();
pstmt = con.prepareStatement(sql);
// 設置參數
// 獲取文本
File file = new File( f:/a.jpg
InputStream in = new FileInputStream(file);
// 設置參數為 2 進制流
pstmt.setBinaryStream(1, in);
// 執行 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);
// 設置參數
pstmt.setInt(1, 2);
// 執行查詢
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();
}
}
}
上述內容就是怎么在 MySQL 中存儲文本和圖片,你們學到知識或技能了嗎?如果還想學到更多技能或者豐富自己的知識儲備,歡迎關注丸趣 TV 行業資訊頻道。
向 AI 問一下細節
正文完