MySQL syntax error using LIMIT command with Prepared Statement in Java

不羁的心 提交于 2019-12-01 05:59:01

问题


I am writing code in Java and I want to take every time I run this code the next line from a MySQL table.The second time I run this code is this.

String timh1 = "1";
String timh2 = "2";
PreparedStatement st = null;
String sqlGrammes = "SELECT SURNAME ,KATHGORIA, AFM , NAME FROM EMPLOYEE LIMIT ?,? ";
try {
    st = connection.prepareStatement(sqlGrammes);
    st.setString(1, timh1);
    st.setString(2, timh2);

But it shows me this error :

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 ''1','2'' at line 1


回答1:


limit accepts integer parameters, so you should use ints, not Strings:

int timh1 = 1;
int timh2 = 2;
PreparedStatement st = null;
String sqlGrammes = "SELECT SURNAME ,KATHGORIA, AFM , NAME FROM EMPLOYEE LIMIT ?,? ";
try {
    st = connection.prepareStatement(sqlGrammes);
    st.setInt(1, timh1); // notice the setInt
    st.setInt(2, timh2); // here too



回答2:


I was able to do it without prepared statement

int i = 0;
    int j = 1;
    sql = "Select SURNAME ,KATHGORIA, AFM , NAME FROM EMPLOYEE limit "+i+ ","+j;

got first row as output.



来源:https://stackoverflow.com/questions/31360027/mysql-syntax-error-using-limit-command-with-prepared-statement-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!