在java中插入sql的命令

时间:2016-12-01 10:10:27

标签: java mysql jdbc

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代码与数据库库连接,并希望从用户获取值并将其保存在学生中。但是表格中保存的值运行此代码后,学生为空,而不是用户输入的值。谁能帮我??提前谢谢

2 个答案:

答案 0 :(得分:0)

可能你应该使用' preparedStmt.executeUpdate()'而不是准备好了Stmt.execute()'。

答案 1 :(得分:-1)

删除后,插入代码工作正常

class insertdata实现ActionListener {public void actionPerformed(ActionEvent e)