在我的窗口應用程序中,我需要執行一系列sqlcommands。如果所有sqlcommands成功執行都沒有問題,但是當第二個或第三個命令出錯時,它會給我造成很大問題,因爲執行1st命令但不執行第二個和第三個命令。在這裏我想要所有的命令執行或沒有。我的代碼如下:如何在C中一次執行一系列sqlcommand#
SqlCommand cmd = new SqlCommand("CREATE TABLE [dbo].[" + textBox8.Text + "_stock]("
+ "[date] [date] NOT NULL PRIMARY KEY CLUSTERED,"
+ "[openingstock] [int] NOT NULL,"
+ "[receipt] [int] NOT NULL,"
+ "[totalstock] [int] NOT NULL,"
+ "[sell] [int] NOT NULL,"
+ "[closingstock] [int] NOT NULL,"
+ ") ON [PRIMARY]", connectionsql);
cmd.ExecuteNonQuery();
cmd.Dispose();
SqlCommand cmd1 = new SqlCommand("insert into " + textBox8.Text + "_stock values(@date,0,0,0,0,0)", connectionsql);
cmd1.Parameters.AddWithValue("date", dateTimePicker3.Value);
cmd1.ExecuteNonQuery();
cmd1.Dispose();
cmd1.Parameters.Clear();
SqlCommand cmd2 = new SqlCommand("insert into rate values ('" + textBox12.Text + "','" + textBox8.Text + "_stock','" + double.Parse(textBox7.Text) + "','" + comboBox4.SelectedItem + "')", connectionsql);
int z = cmd2.ExecuteNonQuery();
cmd2.Dispose();
[SQL注入警報(http://msdn.microsoft.com/en-us/library/ms161953%28v=sql.105%29.aspx) - 你應該不是** **將您的SQL語句連接在一起 - 使用**參數化查詢**來代替以避免SQL注入 –