usingSystem;usingSystem.Data;usingSystem.Data.SqlClient;namespacexyntest{classProgram{publicstaticvoidDisplayDataTable(DataTablemyDataTable){foreach(DataRowmyDataRowinmyD...
using System;
using System.Data;
using System.Data.SqlClient;
namespace xyntest
{
class Program
{
public static void DisplayDataTable(DataTable myDataTable)
{
foreach (DataRow myDataRow in myDataTable.Rows)
{
Console.WriteLine("CustomerID=" + myDataRow["CustomerID"]);
Console.WriteLine("CompanyName=" + myDataRow["CompanyName"]);
Console.WriteLine("ContactName=" + myDataRow["ContactName"]);
Console.WriteLine("Address=" + myDataRow["Address"]);
}
}
//添加add新行
public static void AddRow(DataTable myDataTable)
{
Console.WriteLine("\nAdding a new row with CustomerID of 'KFF'");
DataRow myNewDataRow = myDataTable.NewRow();
myNewDataRow["CustomerID"] = "KFF";
myNewDataRow["CompanyName"] = "T1 Company";
myNewDataRow["ContactName"] = "Jason Price";
myNewDataRow["Address"] = "1 Main Street"; myDataTable.Rows.Add(myNewDataRow); myDataTable.AcceptChanges();
}
public static void Main()
{
string connectionString = "server=localhost;database=Northwind;uid=sa;pwd=sa";
SqlConnection mySqlConnection = new SqlConnection(connectionString);
mySqlConnection.Open();
string selectString = "select CustomerID,CompanyName,ContactName,Address from Customers where CustomerID='ALFKI'";
SqlCommand mySqlCommand = mySqlConnection.CreateCommand();
mySqlCommand.CommandText = selectString;
SqlDataAdapter mySqlDataAdapter = new SqlDataAdapter();
mySqlDataAdapter.SelectCommand = mySqlCommand;
DataSet myDataSet = new DataSet();
Console.WriteLine("Retrieving a row from the Customers table");
mySqlDataAdapter.Fill(myDataSet, "Customers");
DataTable myDataTable = myDataSet.Tables["Customers"];
DisplayDataTable(myDataTable);
AddRow(myDataTable);
DisplayDataTable(myDataTable);
mySqlDataAdapter.Fill(myDataSet,"Customers");
mySqlConnection.Close();
}
}
}
上面的程序myDataSet和myDataTable都有值,可是数据库没有新添加的“KFF”的记录,不知道为什么,哪里错了吗?
改成update可以了
DataSet myDataSet = new DataSet();
SqlCommandBuilder cb = new SqlCommandBuilder(mySqlDataAdapter);
mySqlDataAdapter.Fill(myDataSet, "Customers");
DataTable myDataTable = myDataSet.Tables["Customers"];
DisplayDataTable(myDataTable);
AddRow(myDataTable);
DisplayDataTable(myDataTable);
mySqlDataAdapter.Update(myDataSet, "Customers");
展开