我敢肯定,一定有办法做到这一点,因为ExecuteNonQuery
不会存在,如果你不能改变一次超过一行,但我不知道如何。目前我使用此代码更新值在Customer表:如何在不使用循环的情况下更新表中的多行?
for (int i = 0; i < dataGridView1.RowCount; i++)
{
string connectionString = @"Data Source = A103-17\SQLEXPRESS17; Initial Catalog = CarRental; Integrated Security = True";
string myUpdate = "UPDATE [CarRental].[dbo].[Customer] " +
// "set [CustomerID] = @CustomerID, " +
"set [FirstName] = @FirstName, " +
"[LastName] = @LastName, " +
"[StreetNo] = @StreetNo, " +
"[StreetName]= @StreetName, " +
"[Suburb] = @Suburb, " +
"[State] = @State, " +
"[PostCode] = @PostCode, " +
"[MobPhone] = @MobPhone, " +
"[DriverLicNo] = @DriverLicNo, " +
"[CreditCardType] = @CreditCardType, " +
"[CreditCardNo] = @CreditCardNo, " +
"[ExpDate] = @ExpDate, " +
"[NameOnCreditCard] = @NameOnCreditCard " +
"WHERE [CustomerID] = @CustomerID" +
";";
SqlConnection con = new SqlConnection(connectionString);
using (SqlCommand ApptUpdate = new SqlCommand(myUpdate, con))
{
ApptUpdate.Parameters.AddWithValue("@CustomerID", dataGridView1.Rows[i].Cells["CustomerID"].Value ?? DBNull.Value);
ApptUpdate.Parameters.AddWithValue("@FirstName", dataGridView1.Rows[i].Cells["FirstName"].Value ?? "Null");
ApptUpdate.Parameters.AddWithValue("@LastName", dataGridView1.Rows[i].Cells["LastName"].Value ?? "Null");
ApptUpdate.Parameters.AddWithValue("@StreetNo", dataGridView1.Rows[i].Cells["StreetNo"].Value ?? "Null");
ApptUpdate.Parameters.AddWithValue("@StreetName", dataGridView1.Rows[i].Cells["StreetName"].Value ?? "Null");
ApptUpdate.Parameters.AddWithValue("@Suburb", dataGridView1.Rows[i].Cells["Suburb"].Value ?? "Null");
ApptUpdate.Parameters.AddWithValue("@State", dataGridView1.Rows[i].Cells["State"].Value ?? "Null");
ApptUpdate.Parameters.AddWithValue("@PostCode", dataGridView1.Rows[i].Cells["PostCode"].Value ?? "Null");
ApptUpdate.Parameters.AddWithValue("@MobPhone", dataGridView1.Rows[i].Cells["MobPhone"].Value ?? "Null");
ApptUpdate.Parameters.AddWithValue("@DriverLicNo", dataGridView1.Rows[i].Cells["DriverLicNo"].Value ?? "Null");
ApptUpdate.Parameters.AddWithValue("@CreditCardType", dataGridView1.Rows[i].Cells["CreditCardType"].Value ?? "Null");
ApptUpdate.Parameters.AddWithValue("@CreditCardNo", dataGridView1.Rows[i].Cells["CreditCardNo"].Value ?? "Null");
ApptUpdate.Parameters.AddWithValue("@ExpDate", dataGridView1.Rows[i].Cells["ExpDate"].Value ?? DateTime.Now);
ApptUpdate.Parameters.AddWithValue("@NameOnCreditCard", dataGridView1.Rows[i].Cells["NameOnCreditCard"].Value ?? "Null");
con.Open();
MessageBox.Show(ApptUpdate.ExecuteNonQuery().ToString());
con.Close();
};
}
}
这工作,但在MessageBox会弹出显示值1的每一行,而不是一次显示对应的值有多少行被改变。我无法将循环外的执行移动到外部,所以我无法弄清楚如何从受影响的ExecuteNonQuery
返回的行中得到任何用处。我如何正确使用该功能?
力求不写这样的代码里面查询语句。有很多方法可以避免这种情况。顺便说一句,如果你坚持避免任何ORM或更干净的方式,至少应该尝试使用'DataTable',让你一次完成更新。 – mok
看看这个问题的最新推出的答案︰http://stackoverflow.com/questions/15273057/update-database-with-changes-made-to-datatable-confusion – mok
我不认为你' d能够解释该方法与我的差异以及为什么要使用它?我想我知道该怎么做,但我对此很新,希望能够确定。 –