如何从vb.net插入两个表 [英] how to insert into two tables from vb.net

查看:104
本文介绍了如何从vb.net插入两个表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将两个值插入到我创建的sql数据库的两个表中.在我的vb.net代码中,我的问题是如果我插入它会被插入,但仅在一个表中插入,有时它不会进入内部.

i want to insert two values into two tables of a sql database which i had created. In my vb.net code my problem is if i insert it get insterted but only in one table else sometimes it's not getting inside.

这是我使用的代码:

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

推荐答案

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

You can actually do it in a single command and even wrap it in a transaction like this:

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来查看出了什么问题.像这样:

Next you need to use try/catch on a SqlServerException to see what is going wrong. Something like:

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

还请阅读有关SQL注入的信息.

Also read up on SQL injection.

这篇关于如何从vb.net插入两个表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆