当我在MySQL中插入数据时如何修复'java.sql.SQLException'错误

时间:2019-03-22 18:13:56

标签: java mysql sql

我正在使用prepareStatement,并且出现java.sql.SQLException错误

query = "INSERT INTO instdb (" +
     "id," +
     "name," +
     "username," +
     "descr," +
     "tel," +
     "vk," +
     "ownerId," +
     "query," +
     "postId," +
     "parametr) VALUES" +
     "(?,?,?,?,?,?,?,?,?,?)";
stmt = con.prepareStatement(query);
stmt.setInt(1, maxid);
stmt.setString(2,user.getFull_name());
stmt.setString(3,username);
stmt.setString(4,caption);
stmt.setString(5,longestTel);
stmt.setString(6,vk);
stmt.setString(7,ownerId);
stmt.setString(8,addons.get(j));
stmt.setString(9,postId);
stmt.setString(10,param);

出现stmt.setInt(1, maxid);错误

java.sql.SQLException: Parameter index out of range (1 > number of parameters, which is 0).

编辑1

我替换了stmt = con.prepareStatement(query);并出现新错误:

java.sql.SQLSyntaxErrorException: 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 '?,?,?,?,?,?,?,?,?,?)'

P.S。 那并没有帮助我stackoverflow

2 个答案:

答案 0 :(得分:1)

您忘了初始化stm吗?

stm = con.prepareStatement(query);

其中con是您的Connection对象。

答案 1 :(得分:0)

好像您没有将查询字符串分配给准备好的语句。应该是这样的:

PreparedStatement stmt = con.prepareStatement(query);

stmt.setInt(1, maxid);

等  ... ...