簡體   English   中英

我嘗試在mysql表中插入數據

[英]I am try to insert data in mysql table

我想用單個查詢在2表中插入數據。 bt它給出錯誤

mycode如下所示。

public class Trains extends HttpServlet {
    public void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException {
        response.setContentType("text/html");
        PrintWriter out=response.getWriter();
        int tid=Integer.parseInt(request.getParameter("tid"));
        String tname=request.getParameter("tname");
        String ttype=request.getParameter("ttype");
        String stncode=request.getParameter("stn_code");
        String stnname=request.getParameter("stn_name");
        String availtime=request.getParameter("Avail_time");
        String depttime=request.getParameter("Dep_time");
        String halttime=request.getParameter("Halt_time");
        String dist=request.getParameter("distance");

        String[] avail_day=request.getParameterValues("week");

        try {
            String query="INSERT INTO Train_info(Train_ID,Train_Name,Train_Type,Runs_On) values(?,?,?,?); INSERT INTO Train_route(stn_code,stn_name,arrival_time,Destn_time,Halt_time,Distance) values(?,?,?,?,?,?)";
            Class.forName("com.mysql.jdbc.Driver");
            Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/Railway","root","mysql123");
            PreparedStatement ps=con.prepareStatement(query);

            ps.setInt(1, tid);
            ps.setString(2, tname);
            ps.setString(3, ttype);
            ps.setString(4, stncode);
            ps.setString(5, stnname);
            ps.setString(6, availtime);
            ps.setString(7, depttime);
            ps.setString(8, halttime);
            ps.setString(9, dist);
            for(int i=0;i<avail_day.length;i++){
            ps.setString(10, avail_day[i]);
            }

            int i=ps.executeUpdate();
            if(i>0){
                out.println("Successfully Registration");
                response.sendRedirect("TrainRoute.jsp");
            }
            else{
                out.println("Registration failed");
                response.sendRedirect("Error.java");
            }
        }
        catch(ClassNotFoundException ce){
            ce.printStackTrace();
        }
        catch(Exception e){
            out.println(e);
        }
    }
}

錯誤是:-

java.sql.SQLException:您的SQL語法有錯誤; 在第1行的'INSERT INTO Train_route(stn_code,stn_name,arrival_time,Destn_time,Halt_time,Dist')附近,查看與您的MySQL服務器版本相對應的手冊以使用正確的語法。

查看此內容: Java-Mysql-多個查詢

INSERT INTO您的語法錯誤消息指出query字符串中的第二個插入。 與大多數MySQL驅動程序一樣,MySQL JDBC驅動程序每次對Connection.preparedStatement()調用僅接受一個查詢。

您需要重構代碼以使用兩個准備好的語句,每個表一次。

如果您習慣於使用其他品牌和型號的SQL表服務器,則此限制可能會使您失望。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM