Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/sql-server/25.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何将组合框值与存储在SQL Server中的表值进行比较_Sql_Sql Server_Vb.net - Fatal编程技术网

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

如何将组合框值与存储在SQL Server中的表值进行比较,sql,sql-server,vb.net,Sql,Sql Server,Vb.net,我试图将组合框的值与数据库中已存储的数据进行比较,如果数据不存在,则应通知用户应从列表中选择一条记录或记下数据库中已存在的名称 下面是我为此编写的代码: 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 an

我试图将组合框的值与数据库中已存储的数据进行比较,如果数据不存在,则应通知用户应从列表中选择一条记录或记下数据库中已存在的名称

下面是我为此编写的代码:

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\u Name
中输入数据时,会出现错误
无效列名“”


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

代码中有几个问题。最糟糕的是用于构建sql查询的字符串连接。其次,使用SqlDataAdapter填充数据表只是为了发现记录是否存在,这是一个较小的问题

您可以将代码更改为

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注入攻击的文本。直接将命令与ExecuteScalar一起使用不需要构建数据表。ExecuteScalar返回第一行的第一列(如果有),否则返回为nothing。

还要注意,我没有使用全局连接对象,而是当场构建一个,并通过Using块销毁它。有一种称为连接池的机制,允许像连接这样的对象非常容易和快速地重建。

a)永远不要使用SQL—始终使用SQL参数。b) cboAuthor_名称未在此处引用,不确定该代码与问题的关系。请澄清:pub_名称是文本类型的列?声明一个变量dt,但填充一个pdt。这是一个打字错误吗?@Steve是的,这是一个打字错误刚刚编辑了它,是的,pub_name是text对不起,但是你正在尽可能地用最困难的方式做每件事。例如,对于Publisher,您可以有一个持久数据适配器(以及DT和CommandBuilder)。您可以设置它们,以便它们知道如何读取和保存到数据库。因此,CBO的数据源将是dtPub。如果它不在DT(=不在CBO中),则它是新的。添加新发布服务器时,将数据添加到DT,并
daPub.Update(dtPub)
添加所有新行并更新任何更改的行。一小行代码。我会被点击事件中的所有代码吓坏的。管理基本TBL并不是那么辛苦。请阅读MSDN上的SQLDataAdapter页面。可以“教”他们如何更新和插入到表中。如果您让它挂起(像在Publisher类中)来添加行,只需向DataTable添加一行并更新它即可。DA知道要添加哪些行,更新哪些行。然后,您可以从DT中创建用于搜索、CBO等的视图。您可以轻松地查询DT,查看是否存在出版商或ISBN,每次单击事件都没有大量SQL垃圾。Steve如果条件满足,我可以添加更多
?在这里我刚刚发布了我的代码快照,实际上我有一个作者组合框来检查它是否与发布者名称相同,并且我需要比较表pk(ISBN),它不应该是重复值,如果所有这些都成功了,那么我希望我的记录应该被保存!如果需要检查两个不同的表,则需要两个不同的sql命令。因此,如果您还有一个author表(您需要检查author是否存在),如果您有一个book表来检查ISBN是否存在,那么您需要查找每个表。或者,您应该为用户界面提供固定的选项。不允许从组合框中选择不存在的内容(即:ComboBoxStyle.DropDownList而不是DropDownList),但是如果我选择DropDownList,并且列表中有更多数据,用户将如何查找所有这些数据?这就是为什么我将样式更改为下拉式,以便用户可以从列表中选择一个项目或键入它!然后,您需要在插入新记录之前添加支票。您可以编写一个存储过程,在一次调用中进行所有检查,但在任何情况下,您都需要在插入时进行尝试/捕获,以确保在插入时捕获错误)Steve请检查我是否已更新了问题“如何实现上述场景中提到的要点?”?
        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));