如何从vb.net插入两个表

时间:2011-03-18 18:15:48

标签: sql sql-server vb.net insert

我想在我创建的sql数据库的两个表中插入两个值。在我的vb.net代码中,我的问题是如果我插入它得到插入但只有在一个表中,否则有时它不会进入。

这是我用过的代码:

    c = TextBox1.Text
    sh = TextBox2.Text
    ph = Val(TextBox3.Text)
    ad = RichTextBox1.Text
    ob = Val(TextBox4.Text)
    con = New SqlConnection("Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Documents and Settings\Administrator\My Documents\Visual Studio 2005\Projects\SHOPPROJECT\SHOPPROJECT\shop.mdf;Integrated Security=True;User Instance=True")
    con.Open()

    str1 = " INSERT INTO CUSTOMER VALUES('" & c & " ' , '" & sh & "' ," & ph & ",'" & ad & "' ,'" & TextBox5.Text & "' ) "

    str2 = "INSERT INTO BALANCE VALUES ('" & c & "', " & ob & ")"

    cmd = New SqlCommand

    cmd.Connection = con
    cmd.CommandType = CommandType.Text
    cmd.CommandText = str1
    cmd.ExecuteNonQuery()
    cmd.CommandText = str2
    cmd.ExecuteNonQuery()
    MsgBox("ITEM IS INSERTED", MsgBoxStyle.Information + MsgBoxStyle.OkOnly, "CUSTOMER ADDED")
    TextBox1.Clear()
    TextBox2.Clear()
    TextBox3.Clear()
    TextBox4.Clear()
    TextBox5.Clear()
    RichTextBox1.Clear()

2 个答案:

答案 0 :(得分:2)

您实际上可以在单个命令中执行此操作,甚至将其包装在如下事务中:

str1 = "begin tran; "
str1 &= "INSERT INTO CUSTOMER VALUES('" & c & " ' , '" & sh & "' ," & ph & ",'" & ad & "' ,'" & TextBox5.Text & "' ); "
str1 &= "INSERT INTO BALANCE VALUES ('" & c & "', " & ob & "); "
str1 &= "commit tran; "

cmd = New SqlCommand
cmd.Connection = con
cmd.CommandType = CommandType.Text
cmd.CommandText = str1
cmd.ExecuteNonQuery()

接下来,您需要在SqlServerException上使用try / catch来查看出错的地方。类似的东西:

try
    ' all your sql code
catch (sqlex as SqlException)
    MessageBox.Show(sqlex.Message)

另请阅读SQL注入。

答案 1 :(得分:0)

您不需要使用不同的字符串变量来插入值。你可以这样做:

str1 = " INSERT INTO CUSTOMER VALUES('" & c & " ' , '" & sh & "' ," & ph & ",'" & ad & "' ,'" & TextBox5.Text & "' );"
str1 & = "INSERT INTO BALANCE VALUES ('" & c & "', " & ob & ")"

cmd = New SqlCommand

    cmd.Connection = con
    cmd.CommandType = CommandType.Text
    cmd.CommandText = str1
    cmd.ExecuteNonQuery()