JDBC SQLException

public static void add(String username_, String password)
{
   try {
       conn = DBConnection.getConnection();
       String sql = "insert into userinfo (uid, user, password) values (null,'?','?')";
        pstm = conn.prepareStatement(sql);
        pstm.setString(2,username_);
        pstm.setString(3,password);
        pstm.executeUpdate();
        System.out.println("数据添加成功");
     }catch (SQLException e) {
            e.printStackTrace();
     }
   }
}
        pstm.setString(2,username_);
        pstm.setString(3,password);

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

为什么错?

阅读 2.3k
3 个回答

?号那里的单引号去掉试试

序号从1开始

正解:
1、?占位符中单引号是多余的;
2、参数占位符是从1开始的,不是根据sql中values()中的参数位置为序。第一个?指代的是第1个参数(pstm.setString(1,...),第二个?指代的是第2个参数(pstm.setString(2,...)),以此类推。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题