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 '('1512144017', 'quqiang01' at line 1
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:425)
at com.mysql.jdbc.Util.getInstance(Util.java:408)
at com.mysql.jdbc.SQLError.createBatchUpdateException(SQLError.java:1162)
at com.mysql.jdbc.PreparedStatement.executeBatchedInserts(PreparedStatement.java:1587)
at com.mysql.jdbc.PreparedStatement.executeBatchInternal(PreparedStatement.java:1253)
at com.mysql.jdbc.StatementImpl.executeBatch(StatementImpl.java:970)
Caused by: 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 '('1512144017', 'quqiang01' at line 1
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:425)
at com.mysql.jdbc.Util.getInstance(Util.java:408)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:943)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3973)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3909)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2527)
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2680)
at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2487)
at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:1858)
at com.mysql.jdbc.PreparedStatement.executeUpdateInternal(PreparedStatement.java:2079)
at com.mysql.jdbc.PreparedStatement.executeUpdateInternal(PreparedStatement.java:2013)
at com.mysql.jdbc.PreparedStatement.executeLargeUpdate(PreparedStatement.java:5104)
at com.mysql.jdbc.PreparedStatement.executeBatchedInserts(PreparedStatement.java:1548)
... 5 more

最近在使用JDBC的时候,一个比较坑的细节,就是关于他里面使用PreparedStatement或者Statement 的 addBatch()/executeBatch()的具体实现问题;

不要手贱在你传入的sql语句没末尾加上分号;

具体是这样:

 //以一个批量提交的实现工具举例
// List<List<Object>> lists: 所有数据的list
// List<Object>:单条数据"值"的list public void batchExecutePstamt(String sql, List < List < Object >> lists) {
try {
connection.setAutoCommit(false);
pstmt = connection.prepareStatement(sql);
if (lists != null && !lists.isEmpty()) {
for (List < Object > cList: lists) {
if (cList == null || cList.isEmpty())
continue; for (int i = 0; i < cList.size(); i++) {
pstmt.setObject(i + 1, cList.get(i));
}
pstmt.addBatch();
}
log.info(pstmt.toString());
pstmt.executeBatch();
connection.commit();
}
} catch (SQLException e) {
e.printStackTrace();
}
}

在这里,我们传入大量的需要插入的对象的List<List<Object>>,里面的 List<Object> 就是某一条具体的记录的值;

如果你调用的时候, 在传入sql的时候, 传入了类似于  insert into `tablename` (name,age) values (?,?); 的sql语句
那么他每次addBatch的时候就会在
com.mysql.jdbc.PreparedStatement.addBatch()的创建com.mysql.jdbc.PreparedStatement.BatchParams 然后放进batchedArgs 静态列表里面

  public void addBatch() throws SQLException {
synchronized (checkClosed().getConnectionMutex()) {
if (this.batchedArgs == null) {
this.batchedArgs = new ArrayList<Object>();
} for (int i = 0; i < this.parameterValues.length; i++) {
checkAllParametersSet(this.parameterValues[i], this.parameterStreams[i], i);
} this.batchedArgs.add(new BatchParams(this.parameterValues, this.parameterStreams, this.isStream, this.streamLengths, this.isNull));
}
}

addBatch()

  public class BatchParams {
public boolean[] isNull = null; public boolean[] isStream = null; public InputStream[] parameterStreams = null; public byte[][] parameterStrings = null; public int[] streamLengths = null; BatchParams(byte[][] strings, InputStream[] streams, boolean[] isStreamFlags, int[] lengths, boolean[] isNullFlags) {
//
// Make copies
//
this.parameterStrings = new byte[strings.length][];
this.parameterStreams = new InputStream[streams.length];
this.isStream = new boolean[isStreamFlags.length];
this.streamLengths = new int[lengths.length];
this.isNull = new boolean[isNullFlags.length];
System.arraycopy(strings, 0, this.parameterStrings, 0, strings.length);
System.arraycopy(streams, 0, this.parameterStreams, 0, streams.length);
System.arraycopy(isStreamFlags, 0, this.isStream, 0, isStreamFlags.length);
System.arraycopy(lengths, 0, this.streamLengths, 0, lengths.length);
System.arraycopy(isNullFlags, 0, this.isNull, 0, isNullFlags.length);
}
} PreparedStatement batchedStatement = null;

BatchParams

然后会在最后使用executeBatch()的时候处理 batchedArgs中的 数据

处理的步骤为:
>> com.mysql.jdbc.StatementImpl.executeBatch()
>> com.mysql.jdbc.PreparedStatement.executeBatchInternal()
这里回去判断你设置的一些参数, 比如connection.getRewriteBatchedStatements(), 这个有助于批量数据处理的参数, 需要在jdbc.url连接中设置 rewriteBatchedStatements = true, 不过好像只针对于某个版本(5.2 ?不确定 )以后的数据操作性能有帮助.
在这里会进入一个将多个PreparedStatement转化为 BLUK 模式的一条语句;(bluk模式不知道的请自行百度)

>> com.mysql.jdbc.PreparedStatement.executeBatchedInserts(int)

这里面有一段源码:

 PreparedStatement batchedStatement = null;

 int batchedParamIndex = 1;
long updateCountRunningTotal = 0;
int numberToExecuteAsMultiValue = 0;
int batchCounter = 0;
CancelTask timeoutTask = null;
SQLException sqlEx = null; long[]updateCounts = new long[numBatchedArgs];
//上面不多说 try {
//这句会把初始化我们传进来的sql
//我们传进来的是类似于 insert into tablename (columns…) values (?,?...)这种
//到这里相当于初始化成 INSERT INTO tablename` (`name`, `age`) values (** NOT SPECIFIED **, ** NOT SPECIFIED **);
//然后他会根据顺序传进我们上面所传进的多个已经赋值的PreparedStatement,
batchedStatement = /* FIXME -if we ever care about folks proxying our MySQLConnection */
prepareBatchedInsertSQL(locallyScopedConn, numValuesPerBatch); if (locallyScopedConn.getEnableQueryTimeouts() && batchTimeout != 0 && locallyScopedConn.versionMeetsMinimum(5, 0, 0)) {
timeoutTask = new CancelTask(batchedStatement);
locallyScopedConn.getCancelTimer().schedule(timeoutTask, batchTimeout);
} if (numBatchedArgs < numValuesPerBatch) {
numberToExecuteAsMultiValue = numBatchedArgs;
} else {
numberToExecuteAsMultiValue = numBatchedArgs / numValuesPerBatch;
} int numberArgsToExecute = numberToExecuteAsMultiValue * numValuesPerBatch; for (int i = 0; i < numberArgsToExecute; i++) {
if (i != 0 && i % numValuesPerBatch == 0) {
try {
updateCountRunningTotal += batchedStatement.executeLargeUpdate();
} catch (SQLException ex) {
sqlEx = handleExceptionForBatch(batchCounter - 1, numValuesPerBatch, updateCounts, ex);
} getBatchedGeneratedKeys(batchedStatement);
batchedStatement.clearParameters();
batchedParamIndex = 1; }
//@see 这里是关键
//@see 如果还有后续的PreparedStatement,根据后面的一个参数,那么他就会将batchedStatement设置为:
// INSERT INTO tablename` (`name`, `age`) values("名字1",'23'), (** NOT SPECIFIED **, ** NOT SPECIFIED **); //@see 问题就在这里
//@see 如果你传入的sql :" insert into tablename (columns…) values (?,?...);"是这样的,那么生成的单条语句以及单个PreparedStatement没有任何问题,你拿到数据库执行去也OK
//@see 但是他现在要给你转为BLUK模式的,如果你结尾带了分号,语句就会变成:
// INSERT INTO tablename` (`name`, `age`) values("名字1",'23');, (** NOT SPECIFIED **, ** NOT SPECIFIED **);然后等待下一次填充参数
//@see 多的这个分号就是导致sql语句错误的原因 //@see 有兴趣可以进源码的这个方法看看
batchedParamIndex = setOneBatchedParameterSet(batchedStatement, batchedParamIndex, this.batchedArgs.get(batchCounter++));
} try {
updateCountRunningTotal += batchedStatement.executeLargeUpdate();
} catch (SQLException ex) {
sqlEx = handleExceptionForBatch(batchCounter - 1, numValuesPerBatch, updateCounts, ex);
} getBatchedGeneratedKeys(batchedStatement); numValuesPerBatch = numBatchedArgs - batchCounter;
}
finally {
if (batchedStatement != null) {
batchedStatement.close();
batchedStatement = null;
}
}

关于JDBC的批量操作executeBatch()所引发sql语句异常的更多相关文章

  1. 10.1(java学习笔记)JDBC基本操作(连接,执行SQL语句,获取结果集)

    一.JDBC JDBC的全称是java database connection java数据库连接. 在java中需要对数据库进行一系列的操作,这时就需要使用JDBC. sun公司制定了关于数据库操作 ...

  2. executeBatch()批量执行Sql语句

    executeBatch()方法:用于成批地执行SQL语句,但不能执行返回值是ResultSet结果集的SQL语句,而是直接执行stmt.executeBatch(); addBatch():向批处理 ...

  3. jmert jdbc request支持执行多条sql语句并设置jdbc字符集

    1.jdbc request支持执行多条sql语句 在JDBC Connection Configuration中的sql连接字串中添加如下内容 allowMultiQueries=true 如下图: ...

  4. [疯狂Java]JDBC:PreparedStatement预编译执行SQL语句

    1. SQL语句的执行过程——Statement直接执行的弊病: 1) SQL语句和编程语言一样,仅仅就会普通的文本字符串,首先数据库引擎无法识别这种文本字符串,而底层的CPU更不理解这些文本字符串( ...

  5. 关于No Dialect mapping for JDBC type :-9 hibernate执行原生sql语句问题

    转自博客http://blog.csdn.net/xd195666916/article/details/5419316,同时感谢博主 今天做了个用hibernate直接执行原生sql的查询,报错No ...

  6. 执行sql语句异常...需要的参数与提供的值个数不匹配

    执行mysql语句时,出现以下错误时. 看错误提示,提示说你的sql语句只需要5个参数,而你提供了8个值value,你确定你确实需要8个参数,而你的sql语句却提示说只需要5个参数 这时,请仔细检查一 ...

  7. sql语句异常向数据库插入数据报错

    在php编程向数据库插入数据时报如下错误: [Err] 1064 - You have an error in your SQL syntax; check the manual that corre ...

  8. sql语句 异常 Err] 1064 - You have an error in your SQL syntax;

    在我们开发的工程中,有时候会报[Err] 1064 - You have an error in your SQL syntax; check the manual that corresponds ...

  9. jdbc获取PreparedStatement最终执行的sql语句

    //直接打印PreparedStatement对象 System.out.println(ps); 输出结果: com.mysql.jdbc.JDBC42PreparedStatement@5f205 ...

随机推荐

  1. day 15 - 1 内置函数

    内置函数 作用域相关 locals() globals() #这两组开始容易搞混 print(locals()) #返回本地作用域中的所有名字 print(globals()) #返回全局作用域中的所 ...

  2. python 列表 元组 字典 集合

    列表 lst = [i for i in range(10)] 切片 # 把下标小于2的显示出来 print(lst[:2]) # 把10个数有大到小输出 print(lst[::-1]) # 把下标 ...

  3. 「luogu2486」[SDOI2011] 染色

    https://www.luogu.org/problemnew/show/P2486 轻重链剖分后,问题转化为一个链上的问题: 线段树维护区间内的颜色段数量,左端点.右端点的颜色: 线段树注意事项 ...

  4. PowerDesigner的Table视图同时显示Code和Name的方法[转发]

    PowerDesigner中Table视图同时显示Code和Name,像下图这样的效果: 实现方法:Tools-Display Preference

  5. 【medium】220. Contains Duplicate III

    因为要考虑超时问题,所以虽然简单的for循环也可以做,但是要用map等内部红黑树实现的容器. Given an array of integers, find out whether there ar ...

  6. 关于TabLayout与ViewPager在Fragment中嵌套Fragment使用或配合使用的思考

    注意: 因为继承的是Fragment,所以getSupportFragmentManager()与getFragmentManager()方法无法使用,这里需要用到getChildFragmentMa ...

  7. 1.2低级线程处理API

    并行扩展库相当有用,因为它允许使用更高级的抽象——任务,而不必直接和线程打交道.但有的时候,要处理的代码是在TPL和PLINQ问世(.NET4.0)之前写的.也有可能某个编程问题不能直接使用它们解决, ...

  8. 史上最明白的 NULL、0、nullptr 区别分析(老师讲N篇都没讲明白的东东),今天终于明白了,如果和我一样以前不明白的可以好好的看看...

    C的NULL 在C语言中,我们使用NULL表示空指针,也就是我们可以写如下代码: int *i = NULL; foo_t *f = NULL; 实际上在C语言中,NULL通常被定义为如下: #def ...

  9. PID控制器开发笔记之十二:模糊PID控制器的实现

    在现实控制中,被控系统并非是线性时不变的,往往需要动态调整PID的参数,而模糊控制正好能够满足这一需求,所以在接下来的这一节我们将讨论模糊PID控制器的相关问题.模糊PID控制器是将模糊算法与PID控 ...

  10. C#中用ILMerge合并DLL和exe文件成一个exe文件或者DLL

    ILMerge是一个将多个.NET程序集合并到一个程序集中的实用程序.它既可以作为  开源使用,也可以作为NuGet包使用. 如果您在使用它时遇到任何问题,请与我们联系.(mbarnett _at_ ...