现在的位置: 首页 > 综合 > 正文

java+mysql存储图片或其它大对象到数据库时的两个问题

2018年05月28日 ⁄ 综合 ⁄ 共 1050字 ⁄ 字号 评论关闭
1、当图片文件超过1M的时候,出错如下: 

JDBC错误:Packet for query is too large (1298910 > 1048576). You can change this value on the server by setting the max_allowed_packet' variable. 

这是因为mysql默认一个包最大1M,需要修改my.ini 

max_allowed_packet = 10M 
如文件大小为10的话 max_allowed_packet应该设为两倍以上,否则还是会出现上面的异常 
修改方法: 
1)my-large.ini 中将 max_allowed_packet = 1M(默认为1M)设置为max_allowed_packet = 10M 
2)将max_allowed_packet = 10M复制到my.ini中的 
[mysqld] 

# The TCP/IP Port the MySQL Server will listen on 
port=3306 
max_allowed_packet = 10M 

3)修改配置文件后要重启mysql服务 

2、图片文件的写入时候遇到 

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 

以前可直接运行的程序,后来数据库换了就不能运行,上面的错误提示是参数类型不匹配,在网上查了一下,应该是数据库字符集的类型的问题(现在字符集是gbk), 
将ps.setBinaryStream(2,inputStream,file.length()); 
改为ps.setBytes(2, buf);直接存byte就可以了, 

Java代码  收藏代码
  1. sql="INSERT INTO blobtest(b_title,b_text)VALUES(?,?)";  
  2.   
  3.   
  4. ps.setString(1, file.getName());  
  5. //新建一byte数组  
  6. byte[] buf=new byte[inputStream.available()];  
  7. //将文件读入到byte[]中  
  8. inputStream.read(buf);  
  9. ps.setBytes(2, buf);  
  10. ps.executeUpdate();  

抱歉!评论已关闭.