该楼层疑似违规已被系统折叠 隐藏此楼查看此楼
废话不多说,主要代码如下:
conn = DriverManager.getConnection(DBUtil.url, DBUtil.user, DBUtil.password);
stmt = conn.createStatement();
//上传BLOB类型的字段分3步
//1.修改(或是插入)EMPTY_BLOB()到BLOB字段中
ps = conn.prepareStatement("update z_user set image=EMPTY_BLOB() WHERE rid=?");
ps.setString(1,rid);
ps.executeUpdate();
ps = conn.prepareStatement("SELECT image FROM z_user WHERE rid=? FOR UPDATE");
ps.setString(1,rid);
rs = ps.executeQuery();
// stmt.executeUpdate("update z_user set image=EMPTY_BLOB() WHERE rid='"+rid+"'");
// //2.查出该BLOB字段
// rs = stmt.executeQuery("SELECT image FROM z_user WHERE rid='"+rid+"' FOR UPDATE");
if(rs.next()) {
//将本地文件读到输入流中,写入一个和该文件同样大小的byte数组中
fis = new FileInputStream(path);
// byte[] blobBuf = new byte[blob.getBufferSize()];
byte[] blobBuf = new byte[(int)fis.available()];
System.out.println("--文件大小-(int)fis.available()--"+(int)fis.available());
//3.取出该BLOB字段
BLOB blob = (BLOB)rs.getBlob("image");
//获取此字段的输出流
out = blob.getBinaryOutputStream();
int length = -1;
// while ((length = fis.read(blobBuf)) != -1){
// //将数组中的数据写入输出流
// out.write(blobBuf,0,length);
// }
fis.read(blobBuf);
out.write(blobBuf);
// ps = conn.prepareStatement("update z_user set image=? where rid=?");
// ps.setBlob(1,blob);
// ps.setString(2,rid);
// ps.executeUpdate();
conn.commit();
System.out.println("---blob.length()----"+blob.length());