wang_rx 发表于 2016-10-19 09:54:59

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

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中的

# 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就可以了,

sql="INSERT INTO blobtest(b_title,b_text)VALUES(?,?)";

ps.setString(1, file.getName());
//新建一byte数组
byte[] buf=new byte;
//将文件读入到byte[]中
inputStream.read(buf);
ps.setBytes(2, buf);
ps.executeUpdate();
页: [1]
查看完整版本: java+mysql存储图片或其它大对象到数据库时的两个问题