问题描述
- 发现一个神奇的问题 prepareStatement setString方法的问题
-
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;public class noSelect_Test {
/*
* 非查询sql语句
*/
public static int nonSelect(String sql,String...args){
System.out.println( args.length);//通过工具类获取数据库连接 Connection conn=DBUtils.getConnection(); PreparedStatement ps=null; int rs = 0; try { ps= conn.prepareStatement(sql); for(int i=1;i<=args.length;i++){ int c=i; /* System.out.println( args.length); System.out.println(i); System.out.println(u); ps.setString(i++, u);*/ System.out.println(i); System.out.println(args[c-1]); ps.setString(i, args[c-1]); } rs=ps.executeUpdate(sql); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); }finally{ DBUtils.close(null, ps, conn); } return rs; }
public static void main(String args[]){
String sql="insert into t_login (username,userpwd)values(?,?)";
nonSelect(sql,"57656","25456");}
}以上是操作
下面是
2
kaishi
1
57656
57656
2
25456
25456
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:57)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:526)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:409)
at com.mysql.jdbc.Util.getInstance(Util.java:384)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1054)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3566)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3498)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:1959)
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2113)
at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2562)
at com.mysql.jdbc.StatementImpl.executeUpdate(StatementImpl.java:1664)
at com.mysql.jdbc.StatementImpl.executeUpdate(StatementImpl.java:1583)
at com.vince.jdbc.noSelect_Test.nonSelect(noSelect_Test.java:35)
at com.vince.jdbc.noSelect_Test.main(noSelect_Test.java:49)你们说该怎么搞
解决方案
rs=ps.executeUpdate(sql);改成 rs=ps.executeUpdate();试试
解决方案二:
同意楼上的说法,可以一试。
解决方案三:
ps= conn.prepareStatement(sql);
rs=ps.executeUpdate(sql);
你在构建 PreparedStatement 的时候已经传入了SQL语句 后面就不用传了
因为很有可能前面的SQL里面匹配好的参数值,被后面传入的SQL给替换掉了!
rs=ps.executeUpdate();
这样就好了 还有那个 c 变量是多余的!