我尝试更新到SQL,但它显示此错误"对象引用未设置对象的实例"

时间:2014-04-14 14:47:03

标签: sql-server vb.net

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Dim CON As SqlConnection

    CON = New SqlConnection("Data Source=.;Initial Catalog=PantienDatabase;Integrated Security=True")
    CON.Open()
    Try
        'cmd.CommandText = "UPDATE Patient_Detail SET (Name ='" & TextBoxName.Text & "',Age = '" & TextBoxAge.Text & "',Sex = '" & TextBoxSex.Text & "',Address = '" & TextBoxAddress.Text & "',Check_In = '" & TextBoxCHiN.Text & "',Check_In_Illness = '" & TextBoxCHinL.Text & "',Sevice = '" & TextBoxService.Text & "',Check_out_Illness = '" & TextBoxCHoutL.Text & "',Check_out = '" & TextBoxCHout.Text & "',Transfer = '" & TextBoxTransfer.Text & "',Patient_result = '" & ComboBoxPtr.Text & "') WHERE ID = '" & TextBoxid.Text & "' "
        cmd.CommandText = "UPDATE Patient_Detail SET (Name = @Name, Age = @Age, Sex = @Sex, Address = @Address, Check_In = @Check_In, Check_In_Illness =@Check_in_illness, Sevice =@Service, Check_out_Illness =@Check_out_Illness, Check_out = @Check_out ,Transfer = @Transfer, Patient_result = @Pantient_result WHERE ID = @ID "

        cmd.Parameters.AddWithValue("@ID", TextBoxid.Text)
        cmd.Parameters.AddWithValue("@Name", TextBoxName.Text)
        cmd.Parameters.AddWithValue("@Age", TextBoxAge.Text)
        cmd.Parameters.AddWithValue("@Sex", TextBoxSex.Text)
        cmd.Parameters.AddWithValue("@Address", TextBoxAddress.Text)
        cmd.Parameters.AddWithValue("@Check_In", TextBoxCHiN.Text)
        cmd.Parameters.AddWithValue("@Check_in_illness", TextBoxCHinL.Text)
        cmd.Parameters.AddWithValue("@Service", TextBoxService.Text)
        cmd.Parameters.AddWithValue("@Check_out_Illness", TextBoxCHoutL.Text)
        cmd.Parameters.AddWithValue("@Check_out", TextBoxCHout.Text)
        cmd.Parameters.AddWithValue("@Transfer", TextBoxTransfer.Text)
        cmd.Parameters.AddWithValue("@Pantient_result", ComboBoxPtr.Text)

        cmd.ExecuteNonQuery()
    Catch ex As Exception
        MessageBox.Show(ex.Message)
    End Try
    CON.Close()

1 个答案:

答案 0 :(得分:3)

您不会在任何地方声明cmd。至少,不在那个代码块中。因此,cmd未设置为任何实例。

CON

的声明下添加此内容

Dim cmd as SqlCommand

将其设置为新实例并将CON设置为TRY块顶部的连接:

cmd = New SqlCommand()
cmd.Connection = CON