使用c#在MS Sql Server中插入多行
本文关键字:插入 Server Sql MS 使用 | 更新日期: 2023-09-27 18:17:48
我正试图使用c#将多行插入MS SQL服务器。我的代码将一个值插入到DB中,但随后抛出异常。我是c#新手,如果有任何帮助,我将不胜感激。
我使用的代码:
private int InsertDataintoDB()
{
var dbConnection = new DBConnection();
UserAppList userAppList = new UserAppList();
userAppList.initList();
var sqlString = "Insert into dbo.[OneSiteUserAccess](UserType, ApplicationCode) values(@appuserType,@appCode)";
string connectionString = dbConnection.GetLASCentralWriterConnectionString();
SqlConnection sqlConnection = new SqlConnection(connectionString);
int rowsAffected = 0;
List<USerType_AndAppCode> mylist = userAppList.myList;
try
{
SqlCommand sqlCommand = new SqlCommand();
sqlCommand.Connection = sqlConnection;
sqlCommand.CommandType = CommandType.Text;
sqlCommand.CommandText = sqlString;
sqlConnection.OpenAsync();
mytextArea.Append(sqlConnection.ConnectionTimeout.ToString());
foreach (var user in mylist)
{
sqlCommand.Parameters.AddWithValue("@appuserType", user.UserType);
sqlCommand.Parameters.AddWithValue("@appCode", user.AppCode);
sqlCommand.ExecuteNonQuery();
rowsAffected++;
}
sqlConnection.Close();
}
catch (SqlException e)
{
Console.WriteLine(e.StackTrace);
mytextArea.Append(e.StackTrace);
}
catch (Exception e)
{
Console.WriteLine(e.StackTrace); mytextArea.Append(e.StackTrace);
}
return rowsAffected;
}
}
Error I am get
System.Data.SqlClient.SqlConnection。OnError (SqlException异常,布尔断开连接,动作
1 wrapCloseInAction) at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action
1 wrapCloseInAction)在System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning (TdsParserStateObjectstatobj, Boolean callerHasConnectionLock, Boolean asyncClose) atSystem.Data.SqlClient.TdsParser。TryRun (RunBehavior RunBehavior,SqlCommand cmdHandler, SqlDataReader dataStreamBulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObjectstateObj Boolean&dataReady)System.Data.SqlClient.SqlCommand。FinishExecuteReader (SqlDataReader ds,RunBehavior RunBehavior, String resetOptionsString) atSystem.Data.SqlClient.SqlCommand.RunExecuteReaderTds (CommandBehaviorRunBehavior, RunBehavior,布尔值async, Int32 timeout, Task&asyncWrite, SqlDataReaderds)System.Data.SqlClient.SqlCommand.RunExecuteReader (CommandBehaviorRunBehavior, RunBehavior,布尔返回流,字符串TaskCompletionSource1 completion, Int32 timeout, Task& task, Boolean asyncWrite) at System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(TaskCompletionSource
sendToPipe, Int32超时;布尔asyncWrite) atSystem.Data.SqlClient.SqlCommand.ExecuteNonQuery ()WebApplication_EmptyWebApp1.UserData.InsertDataintoDB ()c:'Users'csaini'Documents'Visual工作室2012 ' ' WebApplication_EmptyWebApp1 ' WebApplication_EmptyWebApp1项目' UserData.aspx.cs:行插入120行:1引用
我认为问题可能是foreach
循环内的AddWithValue
。对于每次迭代,您都要不断地添加相同的参数。你的代码应该是这样的(检查语法):
SqlCommand sqlCommand = new SqlCommand();
sqlCommand.Connection = sqlConnection;
sqlCommand.CommandType = CommandType.Text;
sqlCommand.CommandText = sqlString;
sqlConnection.Open();
mytextArea.Append(sqlConnection.ConnectionTimeout.ToString());
sqlCommand.Parameters.Add("@appuserType", SqlDbType.NVarChar);
sqlCommand.Parameters.Add("@appCode", SqlDbType.NVarChar);
foreach (var user in mylist)
{
sqlCommand.Parameters["@appuserType"].Value = user.UserType;
sqlCommand.Parameters["@appCode"].Value = user.AppCode;
sqlCommand.ExecuteNonQuery();
rowsAffected++;
}
sqlConnection.Close();