如何在此代码中存储多个记录 [英] how can I store multiple record in this code

查看:129
本文介绍了如何在此代码中存储多个记录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

public void SaveProduct()
        {
            SqlConnection con = new SqlConnection(sqlcon);
            con.Open();

 SqlCommand cmd = new SqlCommand("Insert into tbl_Product (BillNo,Prod_Name,Price,Quantity,Sum) values ('" + txtBillNo.Text + "','" + txtprod1.Text + "','" + txtQnt1.Text + "','" + txtPriceUnit1.Text + "','" + txtPrice1.Text + "')," 
+ "('" + txtBillNo.Text + "','" + txtProd2.Text + "','" + txtQnt2.Text + "','" + txtPriceUnit2.Text + "','" + txtPrice2.Text + "')," 

+ "('" + txtBillNo.Text + "','" + txtProd3.Text + "','" + txtQnt3.Text + "','" + txtPriceUnit3.Text + "','" + txtPrice3.Text + "'),"

 + "('" + txtBillNo.Text + "','" + txtProd4.Text + "','" + txtQnt4.Text + "','" + txtPriceUnit4.Text + "','" + txtPrice4.Text + "')," 

+ "('" + txtBillNo.Text + "','" + txtProd5.Text + "','" + txtQnt5.Text + "','" + txtPriceUnit5.Text + "','" + txtPrice5.Text + "')," 

+ "('" + txtBillNo.Text + "','" + txtProd6.Text + "','" + txtQnt6.Text + "','" + txtPriceUnit6.Text + "','" + txtPrice6.Text + "'),"

 + "('" + txtBillNo.Text + "','" + txtProd7.Text + "','" + txtQnt7.Text + "','" + txtPriceUnit7.Text + "','" + txtPrice7.Text + "'),"

 + "('" + txtBillNo.Text + "','" + txtProd8.Text + "','" + txtQnt8.Text + "','" + txtPriceUnit8.Text + "','" + txtPrice8.Text + "'),"

 + "('" + txtBillNo.Text + "','" + txtProd9.Text + "','" + txtQnt9.Text + "','" + txtPriceUnit9.Text + "','" + txtPrice9.Text + "')," 

+ "('" + txtBillNo.Text + "','" + txtProd10.Text + "','" + txtQnt10.Text + "','" + txtPriceUnit10.Text + "','" + txtPrice10.Text + "')", con);
            if (cmd.ExecuteNonQuery() > 0)
            {
                totalCost();
            }
        }



这是一个票据打印项目.要存储最多10条记录,我将使用这些文本框.但是,当我要存储少于十条记录时,会出现错误.因此,如何修改此代码以存储少于10条或最多10条记录.



This is a bill print project. for store maximum 10 record I take these text boxes. But when I want to store less than ten record I get error. So how can I modified this code to store less than 10 or maximum 10 records.

推荐答案

我不会理会此代码.我敢肯定,我会为此说些硬话,但坦率地说,这段代码看起来太糟糕了.
您是否听说过 SQL注入 [
I wouldn''t bother looking at this code. I am sure that I am gonna get some hard words for this, but to be very frank this code look horrible.
Have you ever heard of SQL Injection[^]?

I would rewrite it to make use of stored procedure and better structure.


请使用参数化查询,它更安全,更容易.

您的问题是,当您输入少于10条记录时,某些输入文本框为空,并且您将获得无效的SQL查询.
对于每条记录,您应该首先检查文本框中是否有数据,然后才将数据追加到查询中.
Please use parametrized queries, it''s much safer and easier.

Your problem is that when you enter less than 10 records, some of the input textboxes are empty and you get invalid SQL query.
For each record you should first check if there is data in textbox and only then append data to the query.


这篇关于如何在此代码中存储多个记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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