【问题标题】:how to insert into two tables from vb.net如何从 vb.net 插入两个表
【发布时间】:2011-03-18 18:15:47
【问题描述】:

我想将两个值插入到我创建的 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()

【问题讨论】:

    标签: sql sql-server vb.net insert


    【解决方案1】:

    您实际上可以在单个命令中完成它,甚至可以将其包装在这样的事务中:

    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 注入。

    【讨论】:

      【解决方案2】:

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

      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()
      

      【讨论】:

      • 嘿,它在 str1& 下显示一个错误,它说类型字符 '&' 与声明的数据类型字符串 string 不匹配
      • 抱歉我没有放空格
      • str1和&之间有空格
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多