将列表中的值传递给c#中的SQL服务器 [英] Passing values in list to SQL server in c#
本文介绍了将列表中的值传递给c#中的SQL服务器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
建议任何方式将列表值发送到SQL服务器?
这样,
List< int> iList = new List< int>();
iList.Add(2);
iList.Add(3);
iList。添加(5);
iList.Add(7);
我想将值2,3,5,7添加到a数据库中的列。
解决方案
使用参数化查询;请参阅 https://www.google.com/search?q=sql%20parameter%20c%23 [ ^ ] 。
这有点复杂,如果你的意思是你想把它们作为不同的行值插入它们。
从DataTable做起来很简单 - 只需使用< a href =https://msdn.microsoft.com/en-us/library/ex21zs8x(v=vs.110).aspx> SqlBulkCopy.WriteToServer [ ^ ]但是没有对于List< T>的equivelant ;。
但是,你可以使用它:转换列表到DataTable [ ^ ]或只是使用DataTable开始于。
为什么不简单地循环集合并在每个循环上插入行。使用(System.Data.SqlClient.SqlConnection connection = new System.Data.SqlClient.SqlConnection()){
try {
connection.ConnectionString = connectionString;
connection.Open();
sql = INSERT INTO MyTable(MyColumn)VALUES(@value);
使用(System.Data.SqlClient.SqlCommand command = new System.Data.SqlClient。 SqlCommand(sql,connection)){
command.Parameters.Add( new System.Data.SqlClient.SqlParameter( @ value,
System.Data.SqlDbType.Int));
command.Prepare();
foreach ( int value in iList){
command.Parameters [ @ value]。Value = value ;
command.ExecuteNonQuery();
}
}
...
Suggest any way to send list values to SQL server?
like this,
List<int> iList = new List<int>();
iList.Add(2);
iList.Add(3);
iList.Add(5);
iList.Add(7);
I want to add values 2,3,5,7 to a column in Database.
解决方案
Use parameterised queries; see https://www.google.com/search?q=sql%20parameter%20c%23[^].
It's a little complicated, if you mean you want to INSERT them as different row values.
It's pretty simple to do from a DataTable - just use SqlBulkCopy.WriteToServer[^] but there is no equivelant for a List<T>.
However, you could use this: Converting a List to a DataTable[^] or just use a DataTable to start with.
Why not simply loop the collection and insert the row on each loop. Something like
using (System.Data.SqlClient.SqlConnection connection = new System.Data.SqlClient.SqlConnection()) { try { connection.ConnectionString = connectionString; connection.Open(); sql = "INSERT INTO MyTable (MyColumn) VALUES (@value)"; using (System.Data.SqlClient.SqlCommand command = new System.Data.SqlClient.SqlCommand(sql, connection)) { command.Parameters.Add(new System.Data.SqlClient.SqlParameter("@value", System.Data.SqlDbType.Int)); command.Prepare(); foreach (int value in iList) { command.Parameters["@value"].Value = value; command.ExecuteNonQuery(); } } ...
这篇关于将列表中的值传递给c#中的SQL服务器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文