2016-11-12 6 views
0

1つのクエリで2つのテーブルにデータを挿入したいと思います。それはエラーを与える私はmysqlテーブルにデータを挿入しようとしています

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

+0

一度に2つのテーブルに挿入することはできません –

+0

'ps.setString(10、avail_day [i]);'これは第10パラメータに異なる値を割り当て続けるのは意味がありません –

+1

2つの挿入単一のトランザクションではなく、単一のクエリで実行されます。 –

答えて

1

ラインで 'INSERT INTO Train_route(stn_code、stn_name、ARRIVAL_TIME、Destn_time、Halt_time、ディスト' 近くで使用する権利構文についてはMySQLサーバのバージョンに対応するマニュアルを確認し、この参照してください:Java - Mysql - Multiple query

INSERT INTOあなたの構文エラーメッセージがあなたのquery文字列にのインサートを呼び出します。MySQLのJDBCドライバ、ほとんどのMySQLのドライバーと同様に、唯一のConnection.preparedStatement()コールに呼び出しごとにクエリを受け入れる。

あなたをリファクタリングする必要があります2つのpを使用するコードテーブルごとに1回、文を訂正します。

他のメーカーやモデルのSQLテーブルサーバーとの操作に慣れていた場合は、この制限が原因で発生する可能性があります。

関連する問題