使用netbeans中的jtextfield在SQL Server表中插入数据

时间:2016-06-29 07:08:41

标签: sql sql-server jtextfield netbeans-8

我正在尝试使用以下代码在SQL Server表中插入用户输入的数据,代码运行时没有任何错误,但未插入数据。

try {
    Class.forName(driver);
    Connection con=DriverManager.getConnection(url, user, pass);
    String sql="insert into inventory"
                +"(Product_Code,Product_Name,Quantity,Cost)"
                +"value(?,?,?,?)";
    PreparedStatement pst=con.prepareStatement(sql);
    pst.setString(1, product_code.getText());
    pst.setString(2, product_name.getText());
    pst.setString(3, quantity.getText());
    pst.setString(4, price.getText()); 
    pst.executeUpdate();
    JOptionPane.showMessageDialog(this, "entry successful");    
}                                    
catch(ClassNotFoundException | SQLException | HeadlessException e){
    JOptionPane.showMessageDialog(this, "entry successful"); 
}

2 个答案:

答案 0 :(得分:0)

以下INSERT脚本中的语法错误:

 String sql="insert into inventory"
             +"(Product_Code,Product_Name,Quantity,Cost)"
             +"value(?,?,?,?)";

value(中的错字应为values(,因此您的代码将为:

String sql="insert into inventory"
         +" (Product_Code, Product_Name, Quantity, Cost)"
         +" values (?, ?, ?, ?)";

答案 1 :(得分:0)

根据评论,我建议你试试这段代码:

String url = "jdbc:sqlserver://localhost:1433;databaseName=YourDBName;integratedSecurity=false;user=MyUserName;password=*****;";

try {
    Class.forName(driver);
    Connection con=DriverManager.getConnection(url);

    if (con!= null) {
        System.out.println("Connected");
    }

    String sql="insert into inventory"
                +" (Product_Code,Product_Name,Quantity,Cost)"
                +" values (?,?,?,?)";
    PreparedStatement pst=con.prepareStatement(sql);
    pst.setString(1, product_code.getText());
    pst.setString(2, product_name.getText());
    pst.setInt(3, Integer.parseInt(quantity.getText()));
    pst.setFloat(4, Float.parseFloat(price.getText())); 

    int rowsInserted = pst.executeUpdate();
    if (rowsInserted > 0) {
        System.out.println("A new row was inserted successfully!");
    }

    JOptionPane.showMessageDialog(this, "entry successful");    
}                                    
catch(ClassNotFoundException | SQLException | HeadlessException e){
    JOptionPane.showMessageDialog(this, "entry successful"); 
}