如何从两个表中检索数据时填充文本框?

时间:2015-04-17 03:39:50

标签: mysql vb.net

我正在尝试从两个表中检索数据以填充textboxex,当我点击按钮打印但我收到错误时说:

  

专栏' UID'在where子句中含糊不清。

我有两个名为tableProducts的表,其中包含ProductID,ProductName和ProductPrice,以及包含QuantityID和AvailableQuantity列的tableQuantity。

这是我的代码。

SqlClientConn.Open()

    Dim SQLString As String = "SELECT ProductName,ProductPrice FROM tableProducts INNER JOIN tableQuantity ON tableProducts.ProductID = tableQuantity.QuantityID WHERE ProductID='" & txtid.Text & "'"

    Dim mySqlDataAdapter As MySql.Data.MySqlClient.MySqlDataAdapter = New MySql.Data.MySqlClient.MySqlDataAdapter(SQLString, SqlClientConn)<br>
    Dim ds As New DataSet
    mySqlDataAdapter.Fill(ds)

    If ds.Tables(&quot;tableProducts&quot;).Rows.Count > 0 Then

txtname.Text = ds.Tables(ProductName).Rows(0).Item(0).ToString()
txtprice.Text = ds.Tables(ProductPrice).Rows(0).Item(1).ToString()
txtquantity.Text = ds.Tables(AvailableQuantity).Rows(0).Item(2).ToString()

 End If
    SqlClientConn.Close()

2 个答案:

答案 0 :(得分:1)

ProductID存在于tableProducts和tableProducts的两个表中,因此它表示

where子句中的列是不明确的

SELECT ProductName,ProductPrice FROM tableProducts INNER JOIN tableQuantity ON tableProducts.ProductID = tableQuantity.QuantityID WHERE ProductID='" & txtid.Text & "'"

为tableProducts使用别名 试试这个查询

SELECT ProductName,ProductPrice FROM tableProducts INNER JOIN tableQuantity ON tableProducts.ProductID = tableQuantity.QuantityID WHERE tableProducts.ProductID='" & txtid.Text & "'"

SELECT a.ProductName,a.ProductPrice FROM tableProducts a INNER JOIN tableQuantity ON tableProducts.ProductID = tableQuantity.QuantityID WHERE a.ProductID='" & txtid.Text & "'"

希望这会有所帮助

答案 1 :(得分:0)

我认为DataReader会更简单。这里没有SQL注入。

Dim sql = SELECT ProductName,ProductPrice FROM 
          tableProducts INNER JOIN 
          tableQuantity ON tableProducts.ProductID = tableQuantity.QuantityID
          WHERE tableProducts.ProductID=@pId"
sqlCom = New SQLCommand(sql, SqlClientConn)
sqlCom.Parameters.AddWithValue("@pId", txtid.Text)
SqlClientConn.Open()
Using reader As SQLDataReader = sqlCom.ExecuteReader
  If reader.HasRows Then
    While reader.Read
      txtname.Text = reader("ProductName").ToString
      txtprice.Text = reader("ProductPrice").ToString
      txtquantity.Text = reader("TableQuantity.AvailibleQuantity").ToString
    End While
  End If
End Using