我正在尝试使用c将多行插入ms sql server。我的代码在数据库中插入一个值,但随后抛出一个异常。
我是新来的,希望能得到帮助。
我使用的代码:

 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;
    }
}

我得到的错误
system.data.sqlclient.sqlconnection.onerror(SqlException异常,
布尔断开连接,操作1 wrapCloseInAction) at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action1 wrapcloseinaction)在
system.data.sqlclient.tdsparser.throwexceptionandwarning(tdsparserstateobject
stateobj,boolean callerhasconnectionlock,boolean asyncclose)位于
system.data.sqlclient.tdsparser.tryrun(运行行为运行行为,
SqlCommandCmdhandler,SqlDataReader数据流,
BulkCopySimpleResultSet BulkCopyHandler,TdsParserStateObject
stateobj,boolean&dataready)在
system.data.sqlclient.sqlcommand.finishExecuteReader(SqlDataReader DS,
runbehavior runbehavior,string resetoptionsstring)位于
system.data.sqlclient.sqlcommand.runexecutereadds(命令行为
CmdBehavior,RunBehavior RunBehavior,布尔返回流,布尔
异步,Int32超时,任务和任务,布尔异步写入,SqlDataReader
ds)在
system.data.sqlclient.sqlcommand.runexecutereader(命令行为
CmdBehavior,RunBehavior RunBehavior,布尔返回流,字符串
方法,任务完成源1 completion, Int32 timeout, Task& task, Boolean asyncWrite) at System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(TaskCompletionSource1
完成,字符串methodname,布尔sendtopipe,int32超时,
布尔异步写入)
system.data.sqlclient.sqlcommand.executeNonQuery()位于
中的webapplication_emptyWebApp1.userData.insertDataInToDB()
C:\users\csaini\documents\Visual Studio
2012\projects\webapplication\u emptywebapp1\webapplication\u emptywebapp1\userdata.aspx.cs:line
插入120行:1
块引用

最佳答案

我认为问题可能是AddWithValue循环中的foreach
对于每一次迭代,您都要一遍又一遍地添加相同的参数。
您的代码应该如下所示(检查语法):

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();

关于c# - 使用C#将多行插入到MS Sql Server中,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/33151895/

10-13 02:20