111,129
社区成员
发帖
与我相关
我的任务
分享
/// <summary>
/// 根据学员ID更新学员信息
/// </summary>
/// <param name="student">学员实体</param>
/// <returns>更新数目</returns>
public int UpdateStudentInfoByID(Student student)
{
int amount = -1;
if ( student.ID == 0 || student.Name == string.Empty )
return amount;
try
{
OleDbCommand command = new OleDbCommand();
command.CommandType = CommandType.Text;
command.Connection = DBAssistant.Connection;
command.Parameters.Add("@id", OleDbType.BigInt).Value = student.ID;
command.Parameters.Add("@name", OleDbType.VarChar, 50).Value = student.Name;
command.Parameters.Add("@sex", OleDbType.Boolean).Value = student.Sex == Genders.Male ? true : false;
command.Parameters.Add("@birthday", OleDbType.DBDate).Value = student.Birthday;
command.Parameters.Add("@mobile", OleDbType.VarChar, 20).Value = student.Mobile;
command.Parameters.Add("@address", OleDbType.VarChar, 50).Value = student.Address;
command.CommandText =
"UPDATE StuInfo SET "
+ "SName = @name, Sex = @sex, Birthday = @birthday, Mobile = @mobile, Address = @address "
+ "WHERE ID = @id;";
DBAssistant.OpenTheConnection(); // 打开
amount = command.ExecuteNonQuery(); // 这里一直是 返回 0 ,数据库里也不变化
}
catch ( Exception exp )
{
Console.WriteLine( exp.Message );
throw;
}
finally
{
DBAssistant.ShutTheConnection();
}
return amount;
} // end method UpdateStudentInfoByID
internal class DALTest
{
static void Main(string [] args)
{
Access.StudentService accStuService = new Access.StudentService(); // 数据层
// 学生对象,参数为:“姓名”、“性别”
Models.Student accModify = new School.Models.Student("更新更新更新", Models.Genders.Male);
accModify.ID = 1; // 学生 ID
accModify.Mobile = "3683297"; // 电话
int accAmount = accStuService.UpdateStudentInfoByID(accModify); // 调用更新方法
Console.WriteLine( accAmount.ToString() ); // 返回受影响的行数 (一直是 0 )为什么更新不了
command.Parameters.Add("@name", OleDbType.VarChar, 50).Value = student.Name;
command.Parameters.Add("@sex", OleDbType.Boolean).Value = student.Sex == Genders.Male ? true : false;
command.Parameters.Add("@birthday", OleDbType.DBDate).Value = student.Birthday;
command.Parameters.Add("@mobile", OleDbType.VarChar, 20).Value = student.Mobile;
command.Parameters.Add("@address", OleDbType.VarChar, 50).Value = student.Address;
//这个一定要调到最后,因为你在SQL中最后一个用到
command.Parameters.Add("@id", OleDbType.BigInt).Value = student.ID;
command.CommandText =
"UPDATE StuInfo SET "
+ "SName = ?, Sex = ?, Birthday =?, Mobile = ?, Address = ? "
+ "WHERE ID = ?;";
//这个一定要调到最后,因为你在SQL中最后一个用到
command.Parameters.Add("@id", OleDbType.BigInt).Value = student.ID;