2016-12-01 34 views
1
class insertdata extends insert implements ActionListener 
     { 
      public void actionPerformed(ActionEvent e) 
      { 
       try{ 

        stno=t1.getText(); 
        s_name=t2.getText(); 
        s_email=t3.getText(); 
        bno=t4.getText(); 
        s_no=Integer.parseInt(stno); 
        b_no=Integer.parseInt(bno);} 
        catch(Exception e1){System.out.println(e1);} 
       System.out.println(s_name); 
       try{ 
        Class.forName("com.mysql.jdbc.Driver"); 
        Connection con=DriverManager.getConnection( 
        "jdbc:mysql://localhost:3306/Library","root",""); 


        String query = " insert into Students (s_no,s_name, b_no, s_email)" 
          + " values (?, ?, ?, ?)"; 

          // create the mysql insert preparedstatement 
          PreparedStatement preparedStmt = con.prepareStatement(query); 
          preparedStmt.setInt (1, s_no); 
          preparedStmt.setString (2, s_name); 
          preparedStmt.setInt (3, b_no); 
          preparedStmt.setString(4, s_email); 
          preparedStmt.execute(); 


        con.close(); 
       }catch(Exception e1){ System.out.println(e1);} 
      } 
     } 

     insertdata i=new insertdata(); 
     ba1.addActionListener(i); 


    } 
} 

我已將此java代碼連接到數據庫庫,並希望從用戶處獲取值並將它們保存在學生中。但運行此代碼後保存在表Students中的值爲空,而不是用戶輸入的值。誰能幫我??在此先感謝在java中插入sql命令

+3

使用調試器,並找出什麼事 – Jens

+0

你需要提交條款 – cralfaro

+0

做嘗試調試代碼?並檢查你的變量 –

回答

0

可能您應該使用'preparedStmt.executeUpdate()'而不是'preparedStmt.execute()'。

+0

'execute()'會工作得很好 –

0

取出後延伸插入代碼的工作正常

類insertdata實現的ActionListener {公共無效的actionPerformed(ActionEvent的五)