简体   繁体   English

如何一次将数据插入多个表中

[英]how to insert data into multiple tables at once

I am wondering if the code I have written is the best way to insert data into multiple tables at ones. 我想知道我编写的代码是否是将数据插入多个表中的最佳方法。

For me this is the first time i'am using code to insert data into the database. 对我来说,这是我第一次使用代码将数据插入数据库。
Before i was always using the tools from visual studio to do it. 在我总是使用visual studio的工具之前做到这一点。

So I have 1 textbox and when I enter a product name and press the save button I save the product into 3 tables. 所以我有1个文本框,当我输入产品名称并按下保存按钮时,我将产品保存到3个表格中。

My code works but is this a good way to do it ?? 我的代码有效,但这是一个很好的方法吗?
Is there a better way to do it?? 有没有更好的方法呢?

private void SaveButton_Click(object sender, EventArgs e)
    {
        if (AddProductTables.Text != "")
        { 


        try
        {
            String ConnectionString = @"Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\DataBase\MyStock.mdf;Integrated Security=True;Connect Timeout=30";
            SqlConnection myconnection = new SqlConnection(ConnectionString);
            myconnection.Open();

            SqlCommand StockCommand = myconnection.CreateCommand();
            StockCommand.CommandText = "insert into Stock([Product]) values (@Product)";
            StockCommand.Parameters.AddWithValue("@Product", AddProductTables.Text);

            SqlCommand LandhuisMisjeCommand = myconnection.CreateCommand();
            LandhuisMisjeCommand.CommandText = "insert into LandhuisMisje([Product]) values (@Product)";
            LandhuisMisjeCommand.Parameters.AddWithValue("@Product", AddProductTables.Text);

            SqlCommand TheWineCellarCommand = myconnection.CreateCommand();
            TheWineCellarCommand.CommandText = "insert into TheWineCellar([Product]) values (@Product)";
            TheWineCellarCommand.Parameters.AddWithValue("@Product", AddProductTables.Text);

            StockCommand.ExecuteNonQuery();
            LandhuisMisjeCommand.ExecuteNonQuery();
            TheWineCellarCommand.ExecuteNonQuery();

            myconnection.Close();
            MessageBox.Show("Saved");
        }


        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }


        }
        else
        {
            MessageBox.Show("Insert Product name");

        }
    }

Simply put all the statements into one command separated by semicolon: 只需将所有语句放入一个以分号分隔的命令中:

using (var connection = new SqlConnection(ConnectionString))
using (var command = connection.CreateCommand())
{
    connection.Open();
    command.CommandText = @"insert into Stock([Product]) values (@Product);
                        insert into LandhuisMisje([Product]) values (@Product);
                        insert into TheWineCellar([Product]) values (@Product);"
    command.Parameters.AddWithValue("@Product", AddProductTables.Text);
    command.ExecuteNonQuery()
}

I would suggest you to do multiple separate INSERT in a TRANSACTION 我建议你在TRANSACTION中做多个单独的INSERT

BEGIN TRANSACTION
INSERT [...]
INSERT [...]
COMMIT TRANSACTION

and you will have to first finish procedure for first table then another as shown below :- 你必须首先完成第一张桌子的程序,然后再完成另一张桌子,如下图所示: -

sqlcmd.CommandText = "INSERT INTO Stock([Product]) values (@Product);
  sqlcmd.Parameters.AddWithValue("@Product", AddProductTables.Text);
  sqlCmd.ExecuteNonQuery();
  sqlCmd.Parameters.Clear();
  sqlcmd.CommandText = "INSERT INTO LandhuisMisje([Product]) values (@Product);
  sqlcmd.Parameters.AddWithValue("@Product", AddProductTables.Text);
  sqlCmd.ExecuteNonQuery();

By this way you can achieve by single command variable instead of taking multiple as in your code 通过这种方式,您可以通过单个命令变量实现,而不是像在代码中那样使用多个

write all commandtext, in one statement and used SET instead of using VALUES . 在一个语句中编写所有commandtext并使用SET而不是使用VALUES

SqlCommand command = myconnection.CreateCommand();    
StockCommand.CommandText = "insert into Stock SET [Product]=@Product;
                            insert into LandhuisMisje SET [Product]=@Product;
                            insert into TheWineCellar SET [Product]=@Product";
command.Parameters.AddWithValue("@Product", AddProductTables.Text);
command.ExecuteNonQuery();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM