Data insertion in SQL Server table using jtextfield in netbeans

僤鯓⒐⒋嵵緔 提交于 2019-12-12 04:23:37

问题


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


来源:https://stackoverflow.com/questions/38092655/data-insertion-in-sql-server-table-using-jtextfield-in-netbeans

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!