Data insertion in SQL Server table using jtextfiel

2019-09-10 16:03发布

问题:

I am trying to insert data typed in by user in SQL Server table using below code, the code runs without any error but data is not inserted.

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"); 
}

回答1:

Syntax error in the below INSERT script:

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

Typo in the value( it should be values(, so your code will be:

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


回答2:

Based on commentaries I suggest you to try this code:

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"); 
}