为什么我一直让SQL参数索引超出范围异常?

时间:2015-04-24 01:10:18

标签: java mysql jsp servlets web-applications

我查看了类似的问题,我遵循编写查询以插入数据库的语法,但我一直得到这个异常。我显然没有看到什么。它停止在" insertStatement.setInt(1,schoolID);" 。我读到这意味着查询的语法不正确。请告诉我哪里出错了。我根本看不到它。

package Servlets;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import jpa.entities.School;

/**
 *
 * @author Timothy
 */
@WebServlet(name = "SchoolFormServlet", urlPatterns = {"/SchoolFormServlet"})
public class SchoolFormServlet extends HttpServlet {

    /**
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
     * methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException, ParseException {
        response.setContentType("text/html;charset=UTF-8");
        try (PrintWriter out = response.getWriter()) {
            /* TODO output your page here. You may use following sample code. */
            ServletContext sc = this.getServletContext();
            sc.getAttribute("schoolForm");
            Integer schoolId = Integer.parseInt(request.getParameter("schoolID"));
            String schoolName = request.getParameter("schoolName");
            Integer periods = Integer.parseInt(request.getParameter("periods"));
            Integer repeatDays = Integer.parseInt(request.getParameter("repeatDays"));
            String scheduleBlock = request.getParameter("scheduleBlock");
            Integer semesters = Integer.parseInt(request.getParameter("semesters"));
            String rangeForLunch = request.getParameter("rangeForLunch");
            String schoolYear = request.getParameter("schoolYear");
            initAndExecuteQuery(schoolId,schoolName,semesters,periods,repeatDays,scheduleBlock,rangeForLunch,schoolYear);

            out.println("<!DOCTYPE html>");
            out.println("<html>");
            out.println("<head>");
            out.println("<title>Servlet SchoolFormServlet</title>");            
            out.println("</head>");
            out.println("<body>");
            out.println("<h1>Servlet SchoolFormServlet at " + request.getContextPath() + "</h1>");
            out.println("</body>");
            out.println("</html>");
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {
            processRequest(request, response);
        } catch (ParseException ex) {
            Logger.getLogger(SchoolFormServlet.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /**
     * Handles the HTTP <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {
            processRequest(request, response);
        } catch (ParseException ex) {
            Logger.getLogger(SchoolFormServlet.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

    public void initAndExecuteQuery(Integer schoolID,String schoolName, Integer semesters,Integer periods,Integer repeatDays,String scheduleBlock,String rangeForLunch, String schoolYear) {
      // JDBC driver name and database URL
      String jdbcDriver ="com.mysql.jdbc.Driver";  
      String url ="jdbc:mysql://173.194.104.102:3306/hssp_schema?zeroDateTimeBehavior=convertToNull";
      Connection connection = null;
      ResultSet resultSet = null;
      Statement statement = null;
      //  Database credentials
      String userName = "admin_aamir";
      String passWord = "tommybrown"; 


        try {
            Class.forName("com.mysql.jdbc.Driver").newInstance();
            connection = DriverManager.getConnection(url, userName , passWord);

          // Execute SQL query

         String sql;
         sql = "INSERT INTO School VALUES ('"+schoolID+" ','"+schoolName+" ','"+semesters+" ','"+periods+" ','"+repeatDays+" ','"+scheduleBlock+" ','"+rangeForLunch+" ','"+schoolYear+" ')";
         PreparedStatement insertStatement = connection.prepareStatement(sql);
         insertStatement.setInt(1, schoolID);
         insertStatement.setString(2,schoolName);
         insertStatement.setInt(3,periods);
         insertStatement.setInt(4,repeatDays);
         insertStatement.setString(5,scheduleBlock);
         insertStatement.setString(6,rangeForLunch);
         insertStatement.setString(7,schoolYear);
         insertStatement.executeQuery();
         insertStatement.close();
         connection.close();

        }
        catch (Exception e) {
            e.printStackTrace();

        }



   }


}

4 个答案:

答案 0 :(得分:1)

你需要在SQL字符串中加上问号,告诉它它有参数 - 而不是直接附加它们。

sql = "INSERT INTO School VALUES(?, ?, ? ...)

MySQL连接器实现将使用您设置的参数值替换这些问号(这不仅仅是将其粘贴到您的代码中,因为这会使其容易受到{{3 }})。

答案 1 :(得分:1)

正确的语法是

INSERT INTO TABLENAME(FIELD1,FIELD2,FIELD3)VALUES(?,?,?)

所以你需要第一个parens中的列的名称和相同的数量?在第二。然后你的setX(1,value)语句填写问号在执行之前的位置。

答案 2 :(得分:0)

School( ...... )里面放了你的数据库表列名,在values(?,?,?.....)里面根据你要插入数据库的列名放了问号,对于你当前的情况是8列所以放8个问题标记。

 String sql;
         sql = "INSERT INTO School(schoolID,schoolName,semesters,periods,repeatDays,scheduleBlock,rangeForLunch,schoolYear) VALUES (?,?,?,?,?,?,?,?)";
         PreparedStatement insertStatement = connection.prepareStatement(sql);
         insertStatement.setInt(1, schoolID);
         insertStatement.setString(2,schoolName);
         insertStatement.setInt(3,periods);
         insertStatement.setInt(4,repeatDays);
         insertStatement.setString(5,scheduleBlock);
         insertStatement.setString(6,rangeForLunch);
         insertStatement.setString(7,schoolYear); 
        // you have missing 1 line for number 8 , since you wanted to insert 8 data into 8 column 
         insertStatement.executeQuery();
         insertStatement.close();
         connection.close();

答案 3 :(得分:0)

方法1: 写下面的代码

String sql;
     sql = "INSERT INTO School VALUES ('"+schoolID+" ','"+schoolName+" ','"+semesters+" ','"+periods+" ','"+repeatDays+" ','"+scheduleBlock+" ','"+rangeForLunch+" ','"+schoolYear+" ')";
     PreparedStatement insertStatement = connection.prepareStatement(sql);
int valid = insertStatement.executeUpdate();
if(valid == 1)
   System.out.println("insertion successfull");
else
   System.out.println("problem while inserting data in database");

希望它适合你。它适用于我的情况。

方法2:

编写以下代码

String sql;
     sql = "INSERT INTO School VALUES ('"+schoolID+" ','"+schoolName+" ','"+semesters+" ','"+periods+" ','"+repeatDays+" ','"+scheduleBlock+" ','"+rangeForLunch+" ','"+schoolYear+" ')";
    sql = "INSERT INTO School VALUES(?,?,?,?,?,?,?,?)";
    PreparedStatement insertStatement = connection.prepareStatement(sql);
     insertStatement.setInt(1, schoolID);
     insertStatement.setString(2,schoolName);
     insertStatement.setInt(3,semesters)   // you forgot to write this statement assuming the data types are correct
     insertStatement.setInt(4,periods);
     insertStatement.setInt(5,repeatDays);
     insertStatement.setString(6,scheduleBlock);
     insertStatement.setString(7,rangeForLunch);
     insertStatement.setString(8,schoolYear);

     int valid = insertStatement.executeUpdate();
     if(valid == 1)
          System.out.println("insertion successfull");
     else
          System.out.println("problem while inserting data in database");

希望您了解这两种方法