MySQLSyntaxErrorException when retrieving MetaData for "select ... limit ?,?" prepared query
I'm trying to get metadata from prepared statement after executing query with parameters in "limit" clause:
PreparedStatement ps = conn.prepareStatement("select * from tbl limit ?, ?");
ps.setLong(1, 0);
ps.setLong(2, 10);
ps.execute();
ResultSetMetaData rsmd = ps.getMetaData();
code throws exception in last line:
Exception in thread "main" 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 ''', ''' at line 1
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:39)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:27)
at java.lang.reflect.Constructor.newInstance(Constructor.java:513)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:407)
at com.mysql.jdbc.Util.getInstance(Util.java:382)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1052)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3593)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3525)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:1986)
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2140)
at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2626)
at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:2111)
at com.mysql.jdbc.PreparedStatement.execute(PreparedStatement.java:1362)
at com.mysql.jd开发者_如何转开发bc.PreparedStatement.getMetaData(PreparedStatement.java:2882)
at ...... <my classes>
When I'm skipping retrieving ResultSetMetaData, code works just fine. I can't find in internet and bug database any mentions for a bug.
I've tried folowing versions of connector/J: 5.1.14, 5.1.12, 5.1.9 (Maven dependency).
Server version is 5.0.77
Can anyone help me?
This is because of how prepared statement assigns parameters when you do the "setLong()".
When you use the setters in prepared statement, it encloses the parameters in single quotes .
I am not sure why the "executeQuery" works. You will see a similar exception if you directly execute the following query.
"select * from tbl limit '0', '10'"
Instead use the following.
int startLimit = 0;
int endLimit = 10;
PreparedStatement ps = conn.prepareStatement("select * from tbl limit " + startLimit + " , " + endLimit);
ps.execute();
// you can use "Statement" if you dont have any more parameters
精彩评论