dee*_*392 1 c# visual-web-developer-2010
我正在尝试使用foreach控件循环遍历字符串数组,然后使用每个值在数据库中插入信息.有人可以帮我理解为什么在using子句中我不能使用foreach变量?
string[] ship_ids = ShipsInScope.Split('|');
foreach (string ship_id in ship_ids)
{
using (SqlCommand InsertCommand = new SqlCommand("insert into PROJECT_SHIP (CR_Number, Ship_Id) VALUES (@CR_Number, @CCF_Number)", DBConn))
{
InsertCommand.Parameters.Add("@CR_Number", SqlDbType.NVarChar, 10).Value = CRNumber;
InsertCommand.Parameters.Add("@Ship_Id", SqlDbType.NVarChar, 10).Value = Ship_Id;
InsertCommand.ExecuteNonQuery();
InsertCommand.Dispose();
}
}
Run Code Online (Sandbox Code Playgroud)
C#区分大小写.您的迭代变量是,ship_id但您尝试Ship_Id在循环中使用.
理想情况下,使用C#命名约定(以及其他变量):
// Declared outside the method.
private const string InsertSql =
"insert into PROJECT_SHIP (CR_Number, Ship_Id) " +
"VALUES (@CR_Number, @CCF_Number)";
...
string[] shipIds = ShipsInScope.Split('|');
foreach (string shipId in shipIds)
{
using (SqlCommand command = new SqlCommand(InsertSql, connection))
{
command.Parameters.Add("@CR_Number", SqlDbType.NVarChar, 10)
.Value = crNumber; // Unclear what this means
command.Parameters.Add("@Ship_Id", SqlDbType.NVarChar, 10)
.Value = shipId;
command.ExecuteNonQuery();
}
}
Run Code Online (Sandbox Code Playgroud)
笔记:
camelCase没有下划线Dispose(因为using语句已调用Dispose)| 归档时间: |
|
| 查看次数: |
585 次 |
| 最近记录: |