c# - 使用 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 ! ");
}
解决方案
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 :))
推荐阅读
- prolog - Prolog 如何跳过一个事实
- python - 为什么我会得到 ZeroDivisionError?
- python - Pandas:添加(总和)具有一些不同索引和列的数据帧
- json - 如何从 URL 解析 JSON
- c++ - 为什么使用 int64_t 会给出错误的结果,而对于简单的整数乘法来说,double 可以按预期工作
- elixir - 更改集错误时未重新填充 file_input
- amazon-s3 - 如何快速列出亚马逊 S3 中的几个特定文件
- arabic - 使用 Skia (SkiaSharp) 渲染阿拉伯语文本
- python - 单能伽马射线平均自由程
- ios - 标签栏在 iOS11 iPad 上未使用全宽