您好,登錄后才能下訂單哦!
本篇內(nèi)容介紹了“java jdbc 怎么操作 blob 類型的數(shù)據(jù)”的有關(guān)知識,在實(shí)際案例的操作過程中,不少人都會遇到這樣的困境,接下來就讓小編帶領(lǐng)大家學(xué)習(xí)一下如何處理這些情況吧!希望大家仔細(xì)閱讀,能夠?qū)W有所成!
MySQL中,BLOB是一個二進(jìn)制大型對象,是一個可以存儲大量數(shù)據(jù)的容器,它能容納不同大小的數(shù)據(jù)。
插入BLOB類型的數(shù)據(jù)必須使用PreparedStatement,因?yàn)锽LOB類型的數(shù)據(jù)無法使用字符串拼接寫的。
MySQL的四種BLOB類型(除了在存儲的最大信息量上不同外,他們是等同的)
實(shí)際使用中根據(jù)需要存入的數(shù)據(jù)大小定義不同的BLOB類型。
需要注意的是:如果存儲的文件過大,數(shù)據(jù)庫的性能會下降。
如果在指定了相關(guān)的Blob類型以后,還報(bào)錯:xxx too large,那么在mysql的安裝目錄下,找my.ini文件加上如下的配置參數(shù): max_allowed_packet=16M。同時(shí)注意:修改了my.ini文件之后,需要重新啟動mysql服務(wù)。
//獲取連接Connection conn = JDBCUtils.getConnection(); String sql = "insert into customers(name,email,birth,photo)values(?,?,?,?)"; PreparedStatement ps = conn.prepareStatement(sql);//java項(xiàng)目www.fhadmin.org// 填充占位符ps.setString(1, "張強(qiáng)"); ps.setString(2, "123@126.com"); ps.setDate(3, new Date(new java.util.Date().getTime()));// 操作Blob類型的變量FileInputStream fis = new FileInputStream("xhq.png"); ps.setBlob(4, fis);//執(zhí)行ps.execute(); fis.close(); JDBCUtils.closeResource(conn, ps);
Connection conn = JDBCUtils.getConnection();String sql = "update customers set photo = ? where id = ?"; PreparedStatement ps = conn.prepareStatement(sql);//java項(xiàng)目www.fhadmin.org// 填充占位符// 操作Blob類型的變量FileInputStream fis = new FileInputStream("coffee.png"); ps.setBlob(1, fis); ps.setInt(2, 25); ps.execute(); fis.close(); JDBCUtils.closeResource(conn, ps);
//java項(xiàng)目www.fhadmin.orgString sql = "SELECT id, name, email, birth, photo FROM customer WHERE id = ?"; conn = getConnection(); ps = conn.prepareStatement(sql); ps.setInt(1, 8); rs = ps.executeQuery();if(rs.next()){ Integer id = rs.getInt(1); String name = rs.getString(2); String email = rs.getString(3); Date birth = rs.getDate(4); Customer cust = new Customer(id, name, email, birth); System.out.println(cust); //讀取Blob類型的字段 Blob photo = rs.getBlob(5); InputStream is = photo.getBinaryStream(); OutputStream os = new FileOutputStream("c.jpg"); byte [] buffer = new byte[1024]; int len = 0; while((len = is.read(buffer)) != -1){ os.write(buffer, 0, len); } JDBCUtils.closeResource(conn, ps, rs); if(is != null){ is.close(); } if(os != null){ os.close(); } }
“java jdbc 怎么操作 blob 類型的數(shù)據(jù)”的內(nèi)容就介紹到這里了,感謝大家的閱讀。如果想了解更多行業(yè)相關(guān)的知識可以關(guān)注億速云網(wǎng)站,小編將為大家輸出更多高質(zhì)量的實(shí)用文章!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。