使用NetBeans中的jtextfield在SQL Server表中进行数据插入 [英] Data insertion in SQL Server table using jtextfield in netbeans

查看:180
本文介绍了使用NetBeans中的jtextfield在SQL Server表中进行数据插入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

推荐答案

基于评论,我建议您尝试以下代码:

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

这篇关于使用NetBeans中的jtextfield在SQL Server表中进行数据插入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆