插入2个表格

时间:2014-03-21 08:38:39

标签: mysql vb.net

我有两个表accountpeoplepeople包含有关某人的信息,account是他们的在线帐户。

现在我有了这段代码,但我似乎无法弄清楚如何从在线表单中获取值并将值插入SQL中的两个表中。

Dim SQLStatement As String = "INSERT INTO people(Firstname, Middlename, 
Lastname, uname, pass, type)" & " SELECT ('" & firstname.Value & "',
'" & middlename.Value & "','" & lastname.Value & "', '" & username.Value & 
"','" & password.Value & "','" & type.Value & "') LEFT JOIN people ON account  "

如你所见,它尚未完成。我想问一下如何将 INSERT INTO 用于两个表。我做了一些研究发现了一些LEFT JOIN,但我无法理解。

修改

  Protected Sub btnRegister_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnRegister.Click
    Const SQLStatement As String = "START TRANSACTION; INSERT INTO people(Firstname, Middlename, Lastname) VALUES ( @p0, @p1, @p3); INSERT account(uname, pass, type) VALUES( @p4, @p5,@p6); COMMIT;"
    Using connection As New SqlConnection()
        Dim command As New SqlCommand(SQLStatement, connection)
        command.Parameters.AddWithValue("@p0", firstname.Value)
        command.Parameters.AddWithValue("@p1", middlename.Value)
        command.Parameters.AddWithValue("@p2", lastname.Value)
        command.Parameters.AddWithValue("@p3", username.Value)
        command.Parameters.AddWithValue("@p4", password.Value)
        command.Parameters.AddWithValue("@p5", type.Value)

        connection.Open()
        command.ExecuteNonQuery()
    End Using
    lblNotice.Text = "Successfully Registered!"
    firstname.Value = ""
    middlename.Value = ""
    lastname.Value = ""
    username.Value = ""
    password.Value = ""
End Sub

Connection.open()出错 ConnectionString属性尚未初始化。

1 个答案:

答案 0 :(得分:3)

SQL INSERT语句只能插入到一个对象中,它可以将从多个中选择的数据插入一个。

如果要在跨多个表更新/插入/删除时保持完整性,则需要使用事务。


Const statement As String = @"START TRANSACTION;

INSERT `People` (
    `Firstname`,
    `Middlename`,
    `Lastname`,
    `uname`,
    `pass`,
    `type`)
VALUES (
    @p0,
    @p1,
    @p2,
    @p3,
    @p4,
    @p5);

INSERT `Account` (
    `Firstname`,
    `Middlename`,
    `Lastname`,
    `uname`,
    `pass`,
    `type`)
VALUES (
    @p0,
    @p1,
    @p2,
    @p3,
    @p4,
    @p5);

COMMIT;"

然后您可以将此字符串与DbCommand一起使用并传入参数以避免注入攻击。

Using connection As New DbConnection()
    Dim command As New DbCommand(statement, connection)
    command.Parameters.AddWithValue("@p0", firstname.Value)
    command.Parameters.AddWithValue("@p1", middlename.Value)
    command.Parameters.AddWithValue("@p2", lastname.Value)
    command.Parameters.AddWithValue("@p3", username.Value)
    command.Parameters.AddWithValue("@p4", password.Value)
    command.Parameters.AddWithValue("@p5", type.Value)

    connection.Open()
    command.ExecuteNonQuery()
End Using