如何将组合框值与存储在SQL Server中的表值进行比较

时间:2016-01-10 15:14:27

标签: sql sql-server vb.net

我正在尝试将combobox值与已存储在数据库中的数据进行比较,如果数据不存在,则应通知用户他应该从列表中选择记录或记下名称已存在于数据库中!

以下是我为它编写的代码:

Private Sub btnsave_Click(sender As Object, e As EventArgs) Handles btnsave.Click
    Try
    'Declare new data adapter and new datatable for publisher id & Auhtor id and ISBN
    ' to check record exist already or no
    Dim pda As New SqlDataAdapter
    Dim pdt As DataTable
    Dim matchPub_name As String = cboPub_id.Text
    pda = New SqlDataAdapter("SELECT pub_name FROM publisher WHERE pub_name =@pub_name", cn)
    pdt = New DataTable
    pda.Fill(pdt)


    Dim ada As New SqlDataAdapter
    Dim adt As DataTable
    Dim matchAuthor_name As String = cboAuthor_id.Text
    ada = New SqlDataAdapter("SELECT author_name FROM author WHERE author_name =" & matchAuthor_name, cn)
    adt = New DataTable
    ada.Fill(adt)


    Dim matchISBN As String = txtisbn.Text.ToString
    da = New SqlDataAdapter("SELECT isbn from book WHERE isbn =" & "'" & matchISBN & "'", cn)
    dt = New DataTable
    da.Fill(dt)

    If pdt.Rows.Count = -1 Then
        lblAlert.BackColor = Color.HotPink
        ErrorProvider1.SetError(cboPub_id, _
                                "*Please Select or type available Publishers or register new in Publisher form")
        lblAlert.Text = "Check Respected Error"
        lblInfo.Text = ""
    ElseIf adt.Rows.Count = -1 Then
        lblAlert.BackColor = Color.HotPink
        ErrorProvider1.SetError(cboAuthor_id, _
                                "*Please Select or type available Authors or register new in Author form")
        lblAlert.Text = "Check Respected Error"
        lblInfo.Text = ""
    ElseIf dt.Rows.Count > 0 Then
        lblAlert.BackColor = Color.HotPink
        ErrorProvider1.SetError(cboAuthor_id, _
                                "*a record with provided ISBN already exist in Database. Insert Unique ISBN")
        lblAlert.Text = "Check Respected Error"
        lblInfo.Text = ""
    Else
        'Insert into Book Table
        cmd = New SqlCommand("Insert into book(isbn, book_name, price, rack_no, no_of_books, staff_id, " _
                             & " pub_id, sub_code, author_id) values(@isbn, @book_name, @price, @rack_no, " _
                             & " @no_of_books, @staff_id, @pub_id, @sub_code, @author_id)", cn)
        With cmd.Parameters
            .AddWithValue("@isbn", txtisbn.Text).ToString()
            .AddWithValue("@book_name", txtbook_name.Text)
            .AddWithValue("@price", txtprice.Text)
            .AddWithValue("@rack_no", txtrack_no.Text)
            .AddWithValue("@no_of_books", TxtNo_of_Books.Text)
            .AddWithValue("@staff_id", Convert.ToInt32(cboStaff_id.SelectedValue.ToString()))
            .AddWithValue("@pub_id", Convert.ToInt32(cboPub_id.SelectedValue.ToString()))
            .AddWithValue("@sub_code", cboSub_Code.Text)
            .AddWithValue("@author_id", cboAuthor_id.SelectedValue)
        End With
        cmd.ExecuteNonQuery()

        'Insert into Published_by Table
        cmd = New SqlCommand("Insert into published_by(isbn, pub_id, pub_date, vol_no) " _
                             & " values(@isbn, @pub_id, @pub_date, @vol_no)", cn)
        cmd.Parameters.AddWithValue("@isbn", txtisbn.Text).ToString()
        cmd.Parameters.AddWithValue("@pub_id", Convert.ToInt32(cboPub_id.SelectedValue.ToString()))
        cmd.Parameters.AddWithValue("@pub_date", DateTimePicker1.Text)
        cmd.Parameters.AddWithValue("@vol_no", txtvol_no.Text)
        cmd.ExecuteNonQuery()
        'Insert into Authored_by Table
        cmd = New SqlCommand("Insert into authored_by(isbn, author_id, completion_date) " _
                             & " values(@isbn, @author_id, @completion_date)", cn)
        cmd.Parameters.AddWithValue("@isbn", txtisbn.Text).ToString()
        cmd.Parameters.AddWithValue("@author_id", cboAuthor_id.SelectedValue)
        cmd.Parameters.AddWithValue("@completion_date", dtpCompletion_Date.Text)
        cmd.ExecuteNonQuery()
        'MessageBox.Show("Record Saved Successfully", "Save", MessageBoxButtons.OK, MessageBoxIcon.Information)
        lblAlert.Text = ""
        lblInfo.Text = "Saved"
    End If
    Catch ex As Exception
    MessageBox.Show("Not Completed Because OF The Following Error " & "%" & ex.Message & "%", "Error", _
    '              MessageBoxButtons.OK, MessageBoxIcon.Error)
    End Try

但是当我在cboAuthor_Name中输入数据时,数据库中没有该数据时,会出现错误Invalid column name ' '

如何处理?有什么帮助吗?

2 个答案:

答案 0 :(得分:0)

您的代码中存在一些问题。最糟糕的是构建SQL查询的字符串连接。然后,使用SqlDataAdapter填充DataTable只是为了发现是否存在记录,这是一个较小的一个。

您可以将代码更改为

Private Sub btnsave_Click(sender As Object, e As EventArgs) Handles btnsave.Click

    Dim matchPub_name As String = cboPub_name.Text
    Dim matchAuthor_name As String = cboAuthor_id.Text
    Dim matchISBN As String = txtisbn.Text.ToString

    Using conn = new SqlConnection(....constring here ....)
    Using cmd = new SqlCommand("SELECT pub_name FROM publisher WHERE pub_name = @name", conn)
        conn.Open
        cmd.Parameters.Add("@name", SqlDbType.NVarChar).Value = matchPub_name
        Dim publisherName = cmd.ExecuteScalar()
        if publisherName is Nothing Then
              lblAlert.BackColor = Color.HotPink
              ErrorProvider1.SetError(cboPub_name, _
                                "*Please Select .....")
              lblAlert.Text = "Check Respected Error"
              lblInfo.Text = ""
              Return
        End If

        cmd.CommandText = "SELECT author_name FROM author WHERE author_name = @name"
        cmd.Parameters("@name").Value = matchAuthor_name
        Dim authorName = cmd.ExecuteScalar() 
        if authorName is Nothing Then
            lblAlert.BackColor = Color.HotPink
            ErrorProvider1.SetError(cboAuthor_name, _
                                "*Please Select .....")
            lblAlert.Text = "Check Respected Error"
            lblInfo.Text = ""
            Return
        End If
        cmd.CommandText = "SELECT isbn from book WHERE isbn = @name"
        cmd.Parameters("@name").Value = matchISBN 
        Dim isbnCode = cmd.ExecuteScalar() 
        if isbnCode IsNot Nothing Then
            lblAlert.BackColor = Color.HotPink
            ErrorProvider1.SetError(txtISBN, _
                                "*ISBN Exists .....")
            lblAlert.Text = "Check Respected Error"
            lblInfo.Text = ""
            Return
        End If
        ' Now insert into Book Table '
    End Using
    End Using
End Sub

使用参数是将值传递到数据库的正确方法,而不是构建一个受解析问题的文本(原始代码错过了名称周围的单引号)和Sql Injection攻击。直接使用ExecuteScalar命令不需要构建数据表。 ExecuteScalar返回第一行的第一列(如果有),否则返回为空 另请注意,我不使用全局连接对象,而是在现场构建一个并通过Using块销毁它。有一种称为连接池的机制允许非常容易和快速地重建像Connection这样的对象。

答案 1 :(得分:0)

        con.Open();
        SqlCommand cmd = new SqlCommand("sp_Addbookdetails", con);
        cmd.CommandType = CommandType.StoredProcedure;
        cmd.Parameters.AddWithValue("@class", ddlclass.SelectedValue.ToString());
        cmd.Parameters.AddWithValue("@Booktype", txtbktype.Text);
        cmd.Parameters.AddWithValue("@Quantity", Convert.ToInt32(txtqty.Text));
        cmd.Parameters.AddWithValue("@price", Convert.ToInt32(txtPrice.Text));