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

时间:2015-01-30 06:14:17

标签: c# sql-server database tsql insert

我想知道我编写的代码是否是将数据插入多个表中的最佳方式。

对我而言,这是我第一次使用代码将数据插入数据库 之前我总是使用visual studio中的工具来做它。

所以我有1个文本框,当我输入产品名称并按下保存按钮时,我将产品保存到3个表格中。

我的代码有效,但这是一个很好的方法吗? 有没有更好的方法呢?

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");

        }
    }

4 个答案:

答案 0 :(得分:3)

只需将所有语句放入由分号分隔的一个命令中:

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

答案 1 :(得分:1)

我建议你在TRANSACTION中做多个单独的INSERT

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

然后你必须首先完成第一张桌子的程序然后再完成另一张桌子,如下所示: -

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

通过这种方式,您可以通过单个命令变量来实现,而不是像在代码中那样采用多个

答案 2 :(得分:0)

在一个语句中编写所有命令文本,并使用 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();

答案 3 :(得分:0)

string strConnString = "myconnectionstring"; // get it from Web.config file    
SqlTransaction objTrans = null;    
   
using (SqlConnection objConn = new SqlConnection(strConnString))    
{    
   objConn.Open();    
   objTrans = objConn.BeginTransaction();    
   SqlCommand objCmd1 = new SqlCommand("insert into Stock SET [Product]=@Product;)", objConn);    
   SqlCommand objCmd2 = new SqlCommand("insert into LandhuisMisje SET [Product]=@Product", objConn); 
SqlCommand objCmd3 = new SqlCommand("insert into TheWineCellar SET [Product]=@Product", objConn);   
   try    
   {    
      objCmd1.ExecuteNonQuery();    
      objCmd2.ExecuteNonQuery(); // Throws exception due to foreign key constraint  
      objCmd3.ExecuteNonQuery(); 
      objTrans.Commit();    
   }    
   catch (Exception)    
   {    
      objTrans.Rollback();    
   }    
   finally    
   {    
      objConn.Close();  `enter code here`  
   }    
}