您需要在您的SqlDataAdapter中使用InsertCommand。
編輯:
下面是一個簡單的例子,我颳起。還有很多其他的東西,但是這應該會讓你走。它假定您有一個包含兩列(Foo int,Bar nvarchar(50))的表(dbo.Foos)。
namespace DataAdapterSample
{
using System;
using System.Data;
using System.Data.SqlClient;
class Program
{
static void Main(string[] args)
{
using (SqlConnection connection = new SqlConnection(@"Data Source=[your server];Initial Catalog=[your database];Integrated Security=true;"))
{
using (SqlDataAdapter dataAdapter = new SqlDataAdapter())
{
dataAdapter.SelectCommand = new SqlCommand("select Foo, Bar from dbo.Foos", connection);
dataAdapter.InsertCommand = new SqlCommand("insert into dbo.Foos (Foo, Bar) values (@Foo, @Bar)", connection);
dataAdapter.InsertCommand.Parameters.Add(new SqlParameter("Foo", SqlDbType.Int, 4, "Foo"));
dataAdapter.InsertCommand.Parameters.Add(new SqlParameter("Bar", SqlDbType.NText, 50, "Bar"));
using (DataSet dataSet = new DataSet())
{
dataAdapter.Fill(dataSet);
Console.WriteLine("There are {0} rows in the table", dataSet.Tables[0].Rows.Count);
DataRow newRow = dataSet.Tables[0].NewRow();
newRow["Foo"] = 5;
newRow["Bar"] = "Hello World!";
dataSet.Tables[0].Rows.Add(newRow);
dataAdapter.Update(dataSet);
}
//Just to prove we inserted
using (DataSet newDataSet = new DataSet())
{
dataAdapter.Fill(newDataSet);
Console.WriteLine("There are {0} rows in the table", newDataSet.Tables[0].Rows.Count);
}
}
}
Console.ReadLine();
}
}
}
謝謝您的回答。 可以請你給我寫一個樣本,因爲我嘗試使用'InsertCommand',但我未能。 很多再次感謝! – menachem 2009-11-24 17:07:01