mysql PreparedStatement executeBatch SQL语句的问题

本文介绍了一个关于使用executeBatch进行批量插入时遇到的问题。由于SQL语句末尾的分号导致了java.sql.BatchUpdateException异常。通过调试发现移除最后一个分号可以解决该问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

今天在使用executeBatch时,使用一个很简单的表

CREATE TABLE IF NOT EXISTS `fnbl_dummy` (
  `id` varchar(32) NOT NULL,
  `userid` bigint(20) NOT NULL,
  `last_update` bigint(20) NOT NULL,
  `status` char(1) NOT NULL,
  `p_content` varchar(200) NULL DEFAULT '',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

做批量插入

                        String SQL_INSERT_INTO_FNBL_DUMMY = "INSERT INTO fnbl_dummy(id,userid,last_update,status,p_content) VALUES (?,?,?,?,?);";
                        Connection con = null;
			PreparedStatement ps = null;
			try {
				con = getUserDataSource().getRoutedConnection(userId);
				con.setAutoCommit(false);
				ps = con.prepareStatement(SQL_INSERT_INTO_FNBL_DUMMY);
				
				for (DummyWrapper item : items) {
					Timestamp lastUpdate = item.getLastUpdate();
					if (lastUpdate == null) {
						lastUpdate = new Timestamp(System.currentTimeMillis());
					}
					
					ps.setString(1, item.getId());
					ps.setLong(2, Long.parseLong(this.userId));
					ps.setLong(3, lastUpdate.getTime());
					ps.setString(4, String.valueOf(Def.PIM_STATE_NEW));
					ps.setString(5, StringUtils.left(item.getContent(), SQL_LASTNAME_DIM));
					ps.addBatch();
				}
				
				int []len = ps.executeBatch();
				con.commit();
				return len.length;
			} catch (Exception e) {
				log.error(e.toString());
				throw new DAOException("Error adding dummy items.", e);
			} finally {
				DBTools.close(con, ps, null);
			}
结果运行是单条测试一直OK,多条测试一直提示“java.sql.BatchUpdateException: 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 ”,查找原因竟然是因为SQL语句最后的";"分号问题,无语


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值