如何将字符串列表插入SQL Server数据库的表中

时间:2016-08-14 19:22:10

标签: c# asp.net sql-server ado.net

我有一个包含3列的表和一个主键:

create table tempTable
(
    id int primary key identity,
    name nvarchar(50),
    gender nvarchar(50),
    city nvarchar(50)
)

还有一个像这样的字符串列表:

List<String> list = new List<String>() { "name", "male", "city" };

我想将此列表放入tempTable。我怎么能这样做?

1 个答案:

答案 0 :(得分:1)

你应该这样做:

string query="INSERT INTO tempTable(name, gender, city) VALUES (@name, @gender, @city)";
using (var connection = new SqlConnection(connectionString))
{
    using (SqlCommand command = new SqlCommand())
    {
        command.Connection = connection;
        command.CommandString = query;
        command.CommandType = CommandType.Text;
        command.Parameters.AddWithValue("@name", list[0]);
        command.Parameters.AddWithValue("@gender", list[1]);
        command.Parameters.AddWithValue("@city", list[2]);
        try
        {
            connection.Open();
            command.ExecuteNonQuery();
        }
        catch (SqlException ex)
        {
            // your code...
        }
    }
}