日期:2014-05-18 浏览次数:21040 次
public DataSet UpdateByDataSet(DataSet ds,string strTblName,string strConnection) { SqlConnection conn = new SqlConnection(strConnection); SqlCommand myCommand = new SqlCommand("select * from " + strTblName, conn); SqlDataAdapter myAdapter = new SqlDataAdapter(myCommand ); SqlCommandBuilder myCommandBuilder = new SqlCommandBuilder(myAdapter); myAdapter.InsertCommand = myCommandBuilder .GetInsertCommand(); try { foreach(DataRow dr in ds.Tables[0].Rows) { dr.SetAdded();//.net 2.0以上版本才有,如果你是.net 1.1那没此方法 }//加上这段代码后看能插入吗.这个是把行状态置成了Added conn.Open(); myAdapter.Update(ds,strTblName); ds.AcceptChanges(); conn.Close(); return ds; //数据集的行状态在更新后会都变为: UnChange,在这次更新后客户端要用返回的ds } catch(Exception err) { conn.Close(); throw err; } }
------解决方案--------------------
using System; using System.Data; using System.Data.SqlClient; namespace Microsoft.Samples.SqlServer { class Program { public static void Main(string[] args) // Define and open a connection to AdventureWorks. { using (SqlConnection connection = new SqlConnection(GetConnectionString())) { connection.Open(); // Perform an initial count on the // destination table. SqlCommand commandRowCount = new SqlCommand( "SELECT COUNT(*) FROM " + "dbo.BulkCopyDemoMatchingColumns;", connection); long countStart = System.Convert.ToInt32( commandRowCount.ExecuteScalar()); Console.WriteLine("Starting row count = " + countStart); // Create a table with some rows. DataTable tableNewProducts = MakeTable(); // Set up the bulk copy object. // Note that the column positions in the // source data reader match the column // positions in the destination table so // there is no need to map columns. using (SqlBulkCopy bcp = new SqlBulkCopy(connection)) { bcp.DestinationTableName = "dbo.BulkCopyDemoMatchingColumns"; // Write from the source to // the destination. bcp.WriteToServer(tableNewProducts); } // Perform a final count on the destination // table to see how many rows were added. long countEnd = System.Convert.ToInt32( commandRowCount.ExecuteScalar()); Console.WriteLine("Ending row count = " + countEnd); long countAdded = countEnd - countStart; if (countAdded == 1) { Console.WriteLine("1 row was added.");