簡體   English   中英

VB.net和SQL問題

[英]VB.net and SQL Question

我剛剛開始學習VB.Net和SQL。 現在,我正在創建我的第一個軟件,但是有一個問題:我的數據庫中有兩個表,並且設法將數據從table1傳輸到table2。 我怎樣才能只將特定的行從table1插入table2。 我不想將表1中的所有數據復制到表2中。 我只想復制選定的行。

這是我的代碼:

 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click       
        cmd.CommandText = "INSERT INTO returns(Department, Purpose, Item_details, Requested_by, Approved_by, ReturnDate) SELECT Department, Purpose, Items_Details, Requested_by, Approved_by, Date FROM borrow WHERE Date= '" & Today.Date.ToShortDateString & "';"
        cmd.Connection = con
        Try
            con.Open()
            cmd.ExecuteNonQuery()
        Finally
            con.Close()
        End Try                
End Sub

我有一個列表框,其中的一個源綁定是borrow ,我只希望將選定的項目單行轉移到我的表returns但是我不知道該怎么做。 每當我單擊按鈕時,表borrow所有內容都將復制到表returns

正如其他注釋中所建議的那樣,養成不要對SQL語句中的參數值使用字符串串聯的習慣。

以下代碼演示了如何使用SQL參數並從列表框中獲取行條件。

Private Sub Button1_Click(ByVal sender As System.Object,
                      ByVal e As System.EventArgs
) Handles button1.Click

    ' Note that I am using an XML literal to improve code readability. '
    Dim insertCommand = <xml>
        INSERT INTO returns(
            Department, 
            Purpose, 
            Item_details, 
            Requested_by, 
            Approved_by, 
            ReturnDate
        ) 
        SELECT
            Department, 
            Purpose, 
            Items_Details, 
            Requested_by, 
            Approved_by, 
            Date 
        FROM borrow 
        WHERE BorrowId = @BorrowId;
    </xml>

    Dim param = cmd.CreateParameter()
    param.ParameterName = "@BorrowId"
    param.Value = listBox.SelectedValue

    cmd.CommandText = insertCommand.Value
    cmd.Parameters.Add(param)

    cmd.Connection = con
    Try
        con.Open()
        cmd.ExecuteNonQuery()
    Finally
        con.Close()
    End Try

End Sub

您需要從列表框中獲取選定的行條件,並將其添加到sql的where子句中。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM