我刚刚注意到即使照片存在且我只更新数据,照片也会自动删除。具体来说,我想要一个可用于更新数据或照片的代码,或者两者兼而有之。
qry = "update StudentDetails.Students set StudentName=@StudentName,Day=@Day,Month=@Month,Year=@Year,Age=@Age,DateAdmit=@DateAdmit,Gender=@Gender,GuardianName=@GuardianName,Phone=@Phone,Email=@Email,Address=@Address,City=@City,Region=@Region,Photo = CASE WHEN @Photo IS NULL THEN Photo ELSE @Photo END where StudentId='" & txtStudentID.Text & "'"
cmd = New SqlCommand(qry, cn)
cmd.Parameters.Add(New SqlParameter("@StudentID", Val(txtStudentID.Text)))
cmd.Parameters.Add(New SqlParameter("@StudentName", txtName.Text))
cmd.Parameters.Add(New SqlParameter("@Day", cboDay.Text))
cmd.Parameters.Add(New SqlParameter("@Month", cboMonth.Text))
cmd.Parameters.Add(New SqlParameter("@Year", txtYear.Text))
cmd.Parameters.Add(New SqlParameter("@Age", Val(lblAge.Text)))
cmd.Parameters.Add(New SqlParameter("@DateAdmit", DateTimePicker1.Value)).ToString()
cmd.Parameters.Add(New SqlParameter("@Gender", Gender))
cmd.Parameters.Add(New SqlParameter("@GuardianName", txtGName.Text))
cmd.Parameters.Add(New SqlParameter("@Phone", txtPhone.Text))
cmd.Parameters.Add(New SqlParameter("@Email", txtEmail.Text))
cmd.Parameters.Add(New SqlParameter("@Address", txtAddress.Text))
cmd.Parameters.Add(New SqlParameter("@City", txtTown.Text))
cmd.Parameters.Add(New SqlParameter("@Region", cboRegion.Text))
If img Is Nothing Then
cmd.Parameters.Add(New SqlParameter("@Photo", DBNull.Value))
Else
cmd.Parameters.Add(New SqlParameter("@Photo", img))
End If
cmd.ExecuteNonQuery()
MessageBox.Show("Record successfully Updated", "Updated", MessageBoxButtons.OK, MessageBoxIcon.Informaation)
答案 0 :(得分:0)
这是一个解决方案。替换:
qry = "update StudentDetails.Students set StudentName=@StudentName,Day=@Day,Month=@Month,Year=@Year,Age=@Age,DateAdmit=@DateAdmit,Gender=@Gender,GuardianName=@GuardianName,Phone=@Phone,Email=@Email,Address=@Address,City=@City,Region=@Region,Photo = CASE WHEN @Photo IS NULL THEN Photo ELSE @Photo END where StudentId='" & txtStudentID.Text & "'"
使用:
Dim sbQry As New StringBuilder(1000)
sbQry.Append("update StudentDetails.Students set StudentID=@StudentID,StudentName=@StudentName,Day=@Day,Month=@Month,Year=@Year,Age=@Age,DateAdmit=@DateAdmit,Gender=@Gender,GuardianName=@GuardianName,Phone=@Phone,Email=@Email,Address=@Address,City=@City,Region=@Region")
If img IsNot Nothing Then
sbQry.Append(",Photo=@Photo")
End If
sbQry.Append(" where StudentId='").Append(txtStudentID.Text).Append("'")
cmd = New SqlCommand(sbQry.ToString, cn)
并替换它:
If img Is Nothing Then
cmd.Parameters.Add(New SqlParameter("@Photo", DBNull.Value))
Else
cmd.Parameters.Add(New SqlParameter("@Photo", img))
End If
用这个:
If img IsNot Nothing Then
cmd.Parameters.Add(New SqlParameter("@Photo", img))
End If