简体   繁体   English

VB.net和SQL问题

[英]VB.net and SQL Question

I've just started to learn VB.Net and SQL. 我刚刚开始学习VB.Net和SQL。 Now I'm creating my first software but I have a problem: I have two tables in my database and I managed to transfer data from table1 to table2. 现在,我正在创建我的第一个软件,但是有一个问题:我的数据库中有两个表,并且设法将数据从table1传输到table2。 How can I just insert specific rows from table1 to table2. 我怎样才能只将特定的行从table1插入table2。 I don't want to copy all the data in table1 to table2; 我不想将表1中的所有数据复制到表2中。 I just want to copy the selected rows. 我只想复制选定的行。

Here's my code: 这是我的代码:

 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

I have a listbox which has a sourcebinding which is borrow and I only want the selected items single row to be transferred to my table returns but I don't know how to do it. 我有一个列表框,其中的一个源绑定是borrow ,我只希望将选定的项目单行转移到我的表returns但是我不知道该怎么做。 Whenever I click the button, everything in table borrow will be copied to table returns . 每当我单击按钮时,表borrow所有内容都将复制到表returns

As suggested in other comments is a good idea to get in the habit of not to use string concatenation for parameter values in a SQL statement. 正如其他注释中所建议的那样,养成不要对SQL语句中的参数值使用字符串串联的习惯。

The following code demonstrates how to use SQL parameters and get the row criteria from the list box. 以下代码演示了如何使用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