J'essaie d'insert plusieurs lignes dans le server MS SQL en utilisant C #. Mon code insère une valeur dans la database, mais génère une exception. Je suis nouveau à C # et j'apprécierais toute aide.
Code J'utilise:
private int InsertDataintoDB() { var dbConnection = new DBConnection(); UserAppList userAppList = new UserAppList(); userAppList.initList(); var sqlSsortingng = "Insert into dbo.[OneSiteUserAccess](UserType, ApplicationCode) values(@appuserType,@appCode)"; ssortingng connectionSsortingng = dbConnection.GetLASCentralWriterConnectionSsortingng(); SqlConnection sqlConnection = new SqlConnection(connectionSsortingng); int rowsAffected = 0; List<USerType_AndAppCode> mylist = userAppList.myList; try { SqlCommand sqlCommand = new SqlCommand(); sqlCommand.Connection = sqlConnection; sqlCommand.CommandType = CommandType.Text; sqlCommand.CommandText = sqlSsortingng; sqlConnection.OpenAsync(); mytextArea.Append(sqlConnection.ConnectionTimeout.ToSsortingng()); 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; } }
Erreur que je reçois
System.Data.SqlClient.SqlConnection.OnError (Exception SqlException, Boolean breakConnection, Action
1 wrapCloseInAction) at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action
1 wrapCloseInAction) à System.Data.SqlClient.TdsParser. ThrowExceptionAndWarning (TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose) à System.Data.SqlClient.TdsParser.TryRun (runBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader DATASTREAM, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean & dataReady) à System.Data.SqlClient.SqlCommand.FinishExecuteReader (SqlDataReader ds, RunBehavior runBehavior, Chaîne resetOptionsSsortingng) à System.Data.SqlClient.SqlCommand.RunExecuteReaderTds (CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async, Int32 timeout, Tâche et tâche, Boolean asyncWrite, SqlDataReader ds) à System.Data. SqlClient.SqlCommand.RunExecuteReader (Comm andBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, méthode Ssortingng, TaskCompletionSource1 completion, Int32 timeout, Task& task, Boolean asyncWrite) at System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(TaskCompletionSource
1 completion, Chaîne nomMéthode, Boolean sendToPipe, Int32 timeout, Boolean asyncWrite) à System.Data.SqlClient.SqlCommand.ExecuteNonQuery () à WebApplication_EmptyWebApp1.UserData.InsertDataintoDB () dans c: \ Users \ csaini \ Documents \ Visual Studio 2012 \ Projects \ WebApplication_EmptyWebApp1 \ WebApplication_EmptyWebApp1 \ UserData.aspx.cs: ligne 120rows inséré: 1
- Comment marquer correctement la colonne d'identité avec Entity Framework 6.1?
- EF Seed ne fonctionne pas lorsque datatables sont déjà dans la database
- Requête multi-mappage avec Dapper
- Comment rendre SqlContext.Pipe.Send dans SQLCLR stocké proc travail avec unicode?
- dapper: #tempDB créé mais pas disponible dans la requête suivante
Blockquote
Je pense que le problème peut être le AddWithValue
à l'intérieur de la boucle foreach
. pour chaque itération, vous ajoutez le même paramètre encore et encore. votre code devrait être quelque chose comme ça (vérifiez la syntaxe):
SqlCommand sqlCommand = new SqlCommand(); sqlCommand.Connection = sqlConnection; sqlCommand.CommandType = CommandType.Text; sqlCommand.CommandText = sqlSsortingng; sqlConnection.Open(); mytextArea.Append(sqlConnection.ConnectionTimeout.ToSsortingng()); 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();