简体   繁体   中英

how to insert multiple row of listview into mssqlserver using c#

This code is working but I think something is missing because it only works if I add one row at a time. How can I store many rows at a time?

foreach (ListViewItem item in listView1.Items)
{
    for (int i = 0; i < listView1.Items.Count; i++)
    {
        SqlConnection con = new SqlConnection("Data Source=ZON-PC;Initial Catalog=RestaurantPOSSOC;Integrated Security=True");

        con.Open();

        SqlCommand _sqlcommand = new SqlCommand("insert into OrderInfo (ProductName,Quantity,Price)values('" + listView1.Items[i].SubItems[0].Text + "','" + listView1.Items[i].SubItems[1].Text + "','" + listView1.Items[i].SubItems[2].Text + "')", con);

        SqlDataReader _sqldatareader = _sqlcommand.ExecuteReader();
        _sqldatareader.Read();

       con.Close();
    }
}

There are a couple of things I would change for your routine:

  1. As gmiley commented, you don't need the foreach loop and the for loop, you are doing n*n inserts this way
  2. Connections can be expensive, I would create the connection outside of the foreach loop.
  3. When I am doing updates, I use SqlCommand.ExecuteNonQuery, instead of SqlCommand.ExecuteReader(), since I don't actually expect any rows to come back.

So in pseudocode:

using (connection = new(...))
    con.open
    foreach(item)
        command = new command()
        command.ExecuteNonQuery()

    con.close

Look Here

basically: INSERT INTO Table ( Column1, Column2 ) VALUES ( Value1, Value2 ), ( Value1, Value2 )

Not an answer, but you really should change your starting code to at least this:

SqlConnection con = new SqlConnection("Data Source=ZON-PC;Initial Catalog=RestaurantPOSSOC;Integrated Security=True");
con.Open();

foreach (ListViewItem item in listView1.Items)
{
    SqlCommand _sqlcommand = new SqlCommand("insert into OrderInfo (ProductName,Quantity,Price)values('" + item.SubItems[0].Text + "','" + item.SubItems[1].Text + "','" + item.SubItems[2].Text + "')", con);

    SqlDataReader _sqldatareader = _sqlcommand.ExecuteReader();
    _sqldatareader.Read();
}

con.Close();

And you really also need to parameterize your query and add some exception handling.

First: regardless of what method is used, you really need to clean up the external resources. Both the SqlConnection and SqlCommand objects have a .Dispose() method and should be used in a using() construct / macro. The using handles both the .Dispose() as well as a basic try / finally to ensure that the .Dispose() method is called, even if an error occurs.

Second: if you are using SQL Server 2008 or newer, you should check out Table Valued Parameters (TVPs) as they will eliminate the SQL Injection issues and increase performance.

I have examples of doing this in the following answers:

Add this under button click or any, before that you should open a SqlConnection

conn = new SqlConnection(ConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString); 

foreach (ListViewItem item in lvPOItem.Items)
{
    SqlCommand cmd = new SqlCommand("INSERT INTO PurchasePOItems (PO_ItemName, PO_Specs, PO_PONumber)values(@PO_ItemName, @PO_Specs,@PO_PONumber)", conn);
    conn.Open();
    cmd.Parameters.AddWithValue("@PO_ItemName", item.SubItems[0].Text);
    cmd.Parameters.AddWithValue("@PO_Specs", item.SubItems[1].Text);
    cmd.Parameters.AddWithValue("@PO_PONumber", cbPurchaseOrderNo.Text);
    cmd.ExecuteNonQuery();
    conn.Close();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM