問題描述
我已經在 c# 中創建了一個列表,現在我需要將該列表插入到 SQL Server 2008 中.這可能嗎?請用一個簡單的例子解釋一下.
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.
推薦答案
這是一個簡單的例子:
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();
}
}
}
這只是遍歷列表中的所有項目并使用 ExecuteNonQuery
.
This just loops through all items in the list and executes one insert-command after the other with ExecuteNonQuery
.
編輯:如果您想知道將數組(或列表)插入 sql-server 的最有效方法,您絕對應該閱讀以下內容:http://www.sommarskog.se/arrays-in-sql-2008.html
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.
這篇關于如何將 C sharp 中的列表插入 SQL Server 2008?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!