How to insert list from C sharp into SQL Server 20

2019-01-29 14:33发布

问题:

I have created a list in c#, now I need to insert the list into SQL Server 2008. Is this possible? please explain with a simple example.

回答1:

Here's a simple example:

List<String> list = new List<String>() { "A", "B", "C" };
using (var con = new SqlConnection(connectionString))
{
    con.Open();
    using (var cmd = new SqlCommand("INSERT INTO TABLE(Column)VALUES(@Column)", con))
    {
        cmd.Parameters.Add("@Column", SqlDbType.VarChar);
        foreach (var value in list)
        {
            cmd.Parameters["@Column"].Value = value;
            int rowsAffected = cmd.ExecuteNonQuery();
        }
    }
}

This just loops through all items in the list and executes one insert-command after the other with ExecuteNonQuery.

Edit: If you want to know the most efficient ways to insert arrays(or lists) into sql-server, you should definitely read this: http://www.sommarskog.se/arrays-in-sql-2008.html

If you have a specific question later, you can come back and show what you've tried.