Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/asp.net/35.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何将字符串列表插入SQL Server数据库的表中_C#_Asp.net_Sql Server_Ado.net - Fatal编程技术网

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

C# 如何将字符串列表插入SQL Server数据库的表中,c#,asp.net,sql-server,ado.net,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" }; List

我有一个包含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" };
List List=newlist(){“name”、“male”、“city”};

我想将此列表放入
可诱惑的
。我该怎么做呢?

你应该这样做:

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...
        }
    }
}

你的问题既不清楚,也没有表现出任何努力。临时表真的是临时表吗?您正在使用原始ADO.Net吗?到目前为止你试过什么?有很多方法可以做到,你累了什么?下面是一个链接,它向您展示了将数据插入到表中的一种方法,并为列表中的每个循环提供了一个方法。还有更多的方法。表的名称很诱人。我正在使用原始ado.net。这是我到目前为止的代码。但我知道,这毫无意义。List List=新列表(){“A”、“B”、“C”};字符串qry=“插入可诱惑的值(@Column)”;使用(var cmd=new SqlCommand(qry,connection)){cmd.Parameters.Add(“@Column”,SqlDbType.VarChar”);foreach(列表中的var值){cmd.Parameters[“@Column”].value=value;cmd.ExecuteNonQuery();}@SafayatZisan-与其将其添加为注释,不如编辑您的问题并将其添加到注释中。您应该检查并停止使用
.AddWithValue()
-它可能会导致意外和令人惊讶的结果…哇!我从未遇到过AddWithValue()的问题。但我认为这是一个非常有趣的链接。谢谢:)