mysql blob 写入表_文件存入MYSql表的blob
向MYSql的數據表中存入文件,這看似沒有什么大問題,只要把文件存入longblob字段就行了。但是最近的實踐發現看似簡單的背后其實有很多陷阱。下面就來分享一下我遇到的問題及我的解決辦法。
先介紹一下我的應用,只有兩個頁面upload.jsp和download.jsp。upload.jsp使用common file upload來上傳文件,并將文件存入mysql的數據表的longblob字段。download.jsp則是從數據庫中取出該longblob字段的內容,并寫到瀏覽器客戶端。數據庫的連接我選用tomcat的連接池,url為jdbc:mysql://localhost:3306/test?characterEncoding=gbk。jsp頁面的編碼都為gbk。數據表的結構如下
CREATE TABLE `file` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`filename` varchar(255) CHARACTER SET utf8 NOT NULL,
`content` longblob,
`filetype` varchar(255) CHARACTER SET utf8 NOT NULL,
`size` int(11) DEFAULT NULL,
`ip` varchar(255) CHARACTER SET utf8 NOT NULL,
`date` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00' ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=15 DEFAULT CHARSET=gbk
上傳文件的java代碼如下
request.setCharacterEncoding("gbk");
if("POST".equalsIgnoreCase(request.getMethod())){
DiskFileUpload upload = new DiskFileUpload();
upload.setHeaderEncoding("gbk");
List list = upload.parseRequest(request);
for(FileItem fileItem : list){
if(!fileItem.isFormField()){
String filename = fileItem.getName().replace("\\", "/");
filename = filename.substring(filename.lastIndexOf("/") + 1);
Context envContext = (Context)new InitialContext().lookup("java:/comp/env");
DataSource ds = (DataSource) envContext.lookup("mysqlTest");
Connection conn = ds.getConnection();
PreparedStatement preStmt = conn.prepareStatement("insert into file (filename, filetype, size, content, ip, date) values (?,?,?,?,?,?)");
preStmt.setString(1, filename);
preStmt.setString(2, fileItem.getContentType());
preStmt.setInt(3, (int)fileItem.getSize());
preStmt.setString(5, request.getRemoteAddr());
preStmt.setTimestamp(6, new Timestamp(System.currentTimeMillis()));
preStmt.setBinaryStream(4, fileItem.getInputStream(),(int)fileItem.getSize());
preStmt.executeUpdate();
preStmt.close();
conn.close();
}
}
}
下載文件的代碼如下
Context envContext = (Context)new InitialContext().lookup("java:/comp/env");
DataSource ds = (DataSource) envContext.lookup("mysqlTest");
conn = ds.getConnection();
preStmt = conn.prepareStatement("select * from file where id = ?");
preStmt.setInt(1, id);
rs = preStmt.executeQuery();
if(rs.next()){
response.reset();
response.setContentType(rs.getString("filetype"));
response.setContentLength(rs.getInt("size"));
InputStream ins = null;
OutputStream ous = null;
try{
ins = rs.getBinaryStream("content");
ous = response.getOutputStream();
byte[] b = new byte[1024];
int len = 0;
while((len = ins.read(b))!= -1){
ous.write(b, 0, len);
}
}finally{
if(ous != null) ous.close();
if(ins != null) ins.close();
}
開始上傳一些文本文件沒問題,但是當上傳的文件大于1M時就報出如下異常
com.mysql.jdbc.PacketTooBigException: Packet for query is too large (5553258 > 1048576). You can change this value on the server by setting the max_allowed_packet' variable.
com.mysql.jdbc.MysqlIO.send(MysqlIO.java:3279)
com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:1971)
com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2151)
com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2625)
com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:2119)
com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2415)
com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2333)
com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2318)
org.apache.tomcat.dbcp.dbcp.DelegatingPreparedStatement.executeUpdate(DelegatingPreparedStatement.java:105)
org.apache.tomcat.dbcp.dbcp.DelegatingPreparedStatement.executeUpdate(DelegatingPreparedStatement.java:105)
org.apache.jsp.saveFile2Mysql_jsp._jspService(saveFile2Mysql_jsp.java:111)
org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:388)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:313)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:260)
javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
為了解決這個問題,沒少廢了周折。在網上看到一些解決辦法,但是在我這都不起作用。在Mysql的安裝裝目錄的my.ini文件的【mysqld】節點下添加max_allowed_packet=100M,重啟mysql服務后(可用net stop/start mysql),在mysql客戶端查看時show variables llike “%packet%”,顯示max_allowed_packet 的大小依然是1M。用mysqld --max_allowed_packet=100M結果依然如此。經過不斷嘗試發現了一個問題mysqld啟動后會成為一個后臺運行的進程,當已經有一個mysqld進程在運行時,再次調用mysqld將會被忽略。所以正確的做法是,首先關閉mysql服務,然后查看windows的任務管理器,關閉正在運行的mysqld進程(如果存在),然后再用mysqld --max_allowed_packet=100M來啟動就沒有問題了。然而這個辦法在機器重啟之后就沒有效果了,開機啟動所使用的max_allowed_packet如何改沒有找到解決辦法。
解決了上個問題,在上傳MP3文件時又遇到了一個異常,同樣讓人頭痛,異常信息如下
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for
the right syntax to use near '??2??2è?�?é?±è|‘?Y:r8é–§é?¥\"R??§?^è–?è|??????§??????????‰-??|;?o é?aè?‘t>' at line 1
sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:39)
sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:27)
java.lang.reflect.Constructor.newInstance(Constructor.java:513)
com.mysql.jdbc.Util.handleNewInstance(Util.java:411)
com.mysql.jdbc.Util.getInstance(Util.java:386)
com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1052)
com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3597)
com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3529)
com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:1990)
com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2151)
com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2625)
com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:2119)
com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2415)
com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2333)
com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2318)
org.apache.tomcat.dbcp.dbcp.DelegatingPreparedStatement.executeUpdate(DelegatingPreparedStatement.java:105)
org.apache.tomcat.dbcp.dbcp.DelegatingPreparedStatement.executeUpdate(DelegatingPreparedStatement.java:105)
org.apache.jsp.saveFile2Mysql_jsp._jspService(saveFile2Mysql_jsp.java:111)
org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:388)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:313)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:260)
javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
查資料發現問題的根源在連接數據庫時使用的字符編碼,將url由 jdbc:mysql://localhost:3306/test?characterEncoding=gbk改成url為jdbc:mysql://localhost:3306/test?characterEncoding=utf8問題就解決了。
創作挑戰賽新人創作獎勵來咯,堅持創作打卡瓜分現金大獎總結
以上是生活随笔為你收集整理的mysql blob 写入表_文件存入MYSql表的blob的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: java衍生作用_关于JAVA衍生出的一
- 下一篇: 找第一个只出现一次的字符_leetcod