首页 > 解决方案 > 使用 ADO.NET 如何将数据列表插入 SQL?

问题描述

我有一个数据列表,就像 list=[{id:1,name:"ABC",age:12},{id:2,name:"QWE",age:21}] 我想将这些数据动态插入数据库一样。

我用谷歌搜索并找到了如何插入特定数据。但不知道如何读取列表然后插入这些数据。

string connetionString = null;
            SqlConnection connection;
            SqlCommand command;
            string sql = null;
            connetionString = "Data Source=source;Initial Catalog=testDB;User ID=ABCD;Password=password";
            sql = "INSERT INTO TableName (id,name,age) VALUES('1','ABC',12)";
            connection = new SqlConnection(connetionString);
            try
            {
                connection.Open();;
                command = new SqlCommand(sql, connection);
                command.ExecuteNonQuery();
               
                command.Dispose();
                connection.Close();
            }
            catch (Exception ex)
            {
                Console.WriteLine("Can not open connection ! ");
            }

标签: c#ado.net

解决方案


cnx.Open(); // open cnx 
if(List.Count !=0){ // if List isn't empty 
    for(int i = 0 i < List.Count ;i++)
        {
            // here he will execute one by one 
            string myQuery ="insert into TABLE_NAME values ('"+List[i][0]+"','"+List[i][1]+"','"+List[i][3]+"' ");
            SqlCommand cmd = new SqlCommand(myQuery,cnx);
            cmd.ExecuteNonQuery();
        }
}
// i hope it's help you :))

推荐阅读