使用SqlDataAdapter插入一行

我想用SqlDataAdapter插入一行到数据库中。 我在CustomerOrders数据库中有两个表(Custormers&Orders),有超过一千个logging。 我想创build一个graphics用户界面(TextBoxes),用于将新的客户和订单添加到数据库到其各自的表中。

  • 我应该怎么做?

我想通常遵循的方法是

dataAdapter = new SqlDataAdapter (sqlQuery, conn); dataSet = new DataSet(); da.Fill(dataSet); 

现在从文本框中取值(或使用DataBinding),将新行添加到dataSet中并调用

  da.Update(dataSet); 

但问题是为什么我应该使用da.Fill(dataSet)首先获取所有其他logging到数据集? 我只想添加一个新的logging。

为此,我正在做的是在DataSet中创build数据库的模式。 喜欢这个:

  DataSet customerOrders = new DataSet("CustomerOrders"); DataTable customers = customerOrders.Tables.Add("Customers"); DataTable orders = customerOrders.Tables.Add("Orders"); customers.Columns.Add("CustomerID", Type.GetType("System.Int32")); customers.Columns.Add("FirstName", Type.GetType("System.String")); customers.Columns.Add("LastName", Type.GetType("System.String")); customers.Columns.Add("Phone", Type.GetType("System.String")); customers.Columns.Add("Email", Type.GetType("System.String")); orders.Columns.Add("CustomerID", Type.GetType("System.Int32")); orders.Columns.Add("OrderID", Type.GetType("System.Int32")); orders.Columns.Add("OrderAmount", Type.GetType("System.Double")); orders.Columns.Add("OrderDate", Type.GetType("System.DateTime")); customerOrders.Relations.Add("Cust_Order_Rel", customerOrders.Tables["Customers"].Columns["CustomerID"], customerOrders.Tables["Orders"].Columns["CustomerID"]); 

我使用DataBinding将这些列绑定到相应的文本框。 现在我很困惑! 接下来我应该做什么? 如何使用插入命令? 因为我没有给任何dataAdapter.SelectCommand所以dataAdapter.Update()不会工作我猜。 请build议一个正确的方法。

使用“0 = 1”筛选器设置select命令,并使用SqlCommandBuilder,以便为您自动生成插入命令。

 var sqlQuery = "select * from Customers where 0 = 1"; dataAdapter = new SqlDataAdapter(sqlQuery, conn); dataSet = new DataSet(); dataAdapter.Fill(dataSet); var newRow = dataSet.Tables["Customers"].NewRow(); newRow["CustomerID"] = 55; dataSet.Tables["Customers"].Rows.Add(newRow); new SqlCommandBuilder(dataAdapter); dataAdapter.Update(dataSet); 

你可以用一个空集填充数据集,例如:

 da = new SqlDataAdapter ("SELECT * FROM Customers WHERE id = -1", conn); dataSet = new DataSet(); da.Fill(dataSet); 

然后你添加你的行并调用更新。

对于这个场景,尽pipe最好不要使用SqlDataAdapter 。 而是直接使用SqlCommand对象进行插入。 (更好的是,使用LINQ to SQL或任何其他ORM)

 SqlConnection con = new SqlConnection("Data Source=(local);Initial Catalog=test;Integrated Security=True"); SqlDataAdapter da=new SqlDataAdapter("Insert Into Employee values("+textBox1.Text+",'"+textBox2.Text+"','"+textBox3.Text+"',"+textBox4.Text+")",con); DataSet ds = new DataSet(); da.Fill(ds); 

我必须做第一次。 你可以试试。 它运作良好。