我在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();
第二次执行循环失败
非常感谢
答案 0 :(得分: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();
}