2

我在 C# 中有一个方法,它执行一些查询以插入事务内的数据库中。

我想要做的是一个循环插入几个“电话号码”

// Creates the transaction
dbTransaction = dbConnection.DbConnection.BeginTransaction(System.Data.IsolationLevel.ReadCommitted);

// Creates the sql command
dbCommand = factory.CreateCommand();
dbCommand.Connection = dbConnection.DbConnection;
dbCommand.Transaction = dbTransaction;    

...逻辑的东西

// Inserts the phone
foreach (PlacePhoneDTO placePhoneDTO in placePhoneList)
{
    dbCommand.CommandText = sqlStatementPhone.ToString();
    // Adds the parameters
    AddParameter<int>("@PlaceID", placeID, ref dbCommand);
    AddParameter<string>("@PhoneNumber", placePhoneDTO.phoneNumber, ref dbCommand);
    dbCommand.ExecuteNonQuery();
}

dbTransaction.Commit();

第二次执行循环失败

非常感谢

4

1 回答 1

2

您要么必须清除命令参数,如 slugster 在他的评论中建议的。您也可以将命令文本移到循环之外,因为它始终相同

dbCommand.CommandText = sqlStatementPhone.ToString();

foreach (PlacePhoneDTO placePhoneDTO in placePhoneList)
{
    dbCommand.Parameters.Clear();

    // Adds the parameters
    AddParameter<int>("@PlaceID", placeID, ref dbCommand);
    AddParameter<string>("@PhoneNumber", placePhoneDTO.phoneNumber, ref dbCommand);

    dbCommand.ExecuteNonQuery();
}

或像这样在循环内重新创建命令:

foreach (PlacePhoneDTO placePhoneDTO in placePhoneList)
{
    dbCommand = factory.CreateCommand();
    dbCommand.Connection = dbConnection.DbConnection;
    dbCommand.Transaction = dbTransaction;  
    dbCommand.CommandText = sqlStatementPhone.ToString();

    // Adds the parameters
    AddParameter<int>("@PlaceID", placeID, ref dbCommand);
    AddParameter<string>("@PhoneNumber", placePhoneDTO.phoneNumber, ref dbCommand);
    dbCommand.ExecuteNonQuery();
}
于 2012-12-18T14:03:25.220 回答