SqlConnection con = new SqlConnection();
con.ConnectionString = @"Data Source=MYDATASOURCE";
con.Open();
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "Insert into [Voorraad] values(@IngredientID,
@AantalInVoorraad, @MinimumVoorraad";
cmd.Parameters.AddWithValue("@IngredientID", txt_ID.Text);
cmd.Parameters.AddWithValue("@AantalInVoorraad", txt_aantal.Text);
cmd.Parameters.AddWithValue("@MinimumVoorraad", txt_minimum.Text);
cmd.Connection = con;
cmd.ExecuteNonQuery();
cmd.Parameters.Clear();
cmd.CommandText = "insert into [Ingredient] values(@IngredientID, @IngredientNaam";
cmd.Parameters.AddWithValue("@IngredientID", txt_ID.Text);
cmd.Parameters.AddWithValue("@IngredientNaam", txt_ingredient.Text);
cmd.ExecuteNonQuery();
我想将数据插入表Voorraad和Ingredient。在Voorraad表格中,必须先将IngredientID,AantalInVoorraad,MinimumVoorraad和Categorie放入表格中。
在表中,必须有一个新的Ingredientnaam。当我填写文本框并点击按钮插入后,我得到错误: System.Data.SqlClient.SqlException:' @ MinimumVoorraad'附近的语法不正确。' 请帮帮我!
I've edited to this:
SqlConnection con = new SqlConnection();
con.ConnectionString = @"Data Source=
con.Open();
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "Insert into [Voorraad] values(@IngredientID,
@AantalInVoorraad, @MinimumVoorraad)";
cmd.Parameters.AddWithValue("@IngredientID", txt_ID.ID);
cmd.Parameters.AddWithValue("@AantalInVoorraad", txt_aantal.Text);
cmd.Parameters.AddWithValue("@MinimumVoorraad", txt_minimum.Text);
cmd.Connection = con;
cmd.ExecuteNonQuery();
cmd.Parameters.Clear();
cmd.CommandText = "insert into [Ingredient] values(@IngredientID,
@IngredientNaam)";
cmd.Parameters.AddWithValue("@IngredientID", txt_ID.ID);
cmd.Parameters.AddWithValue("@IngredientNaam", txt_ingredient.Text);
cmd.ExecuteNonQuery();
有没有人知道将数据插入数据库中的多个表的另一种方法?我在整个互联网上搜索了答案,但我找不到合适的解决方案。
答案 0 :(得分:2)
Introducing ASP.NET Web Pages - Entering Database Data by Using Forms
cmd.CommandText = "Insert into [Voorraad] (IngredientID, AantalInVoorraad, MinimumVoorraad) values(@IngredientID, @AantalInVoorraad, @MinimumVoorraad)";
和
cmd.CommandText = "insert into [Ingredient] (IngredientID, IngredientNaam) values(@IngredientID, @IngredientNaam)";
答案 1 :(得分:0)
您的插入语句缺少值的结束括号。
为SQlConnection和SQLCommand添加using语句,将使其更易于阅读和调试。
using (SqlConnection con = new SqlConnection(@"Data Source=MYDATASOURCE"))
{
con.Open();
using(SqlCommand cmd = new SqlCommand(
"Insert into [Voorraad] values(@IngredientID, @AantalInVoorraad, @MinimumVoorraad)", con))
{
cmd.Parameters.AddWithValue("@IngredientID", txt_ID.Text);
cmd.Parameters.AddWithValue("@AantalInVoorraad", txt_aantal.Text);
cmd.Parameters.AddWithValue("@MinimumVoorraad", txt_minimum.Text);
cmd.ExecuteNonQuery();
}
using(SqlCommand cmd = new SqlCommand(
"insert into [Ingredient] values(@IngredientID, @IngredientNaam)", con))
{
cmd.Parameters.AddWithValue("@IngredientID", txt_ID.Text);
cmd.Parameters.AddWithValue("@IngredientNaam", txt_ingredient.Text);
cmd.ExecuteNonQuery();
}
}