读书人

求C#操作ACCESS的例子解决办法

发布时间: 2012-01-23 21:57:28 作者: rapoo

求C#操作ACCESS的例子


[解决办法]
namespace CustomerEditor
{
public partial class Form1 : Form
{
private OleDbConnection _connection;
public Form1()
{
InitializeComponent();
}
private void menuDataConnect_Click(object sender, EventArgs e)
{
Connect();
}
public void Connect()
{
//Diaplay the dialog.....
if (DialogResult.OK == dialogOpenFile.ShowDialog(this))
{
//try to connect
try
{
//Create a new connection string......
string connectionString = string.Format(
"Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};User ID=;Password=;",
dialogOpenFile.FileName);
//Create a connection
OleDbConnection newConnection =
new OleDbConnection(connectionString);
//try and open it.....
newConnection.Open();
// Store it for use....
_connection = newConnection;
}
catch (Exception ex)
{
//Report the problem....
HandleException("A connection could not be made.", ex);
}
}
}
public void HandleException(string message, Exception ex)
{
//Display a message box...
MessageBox.Show(this, string.Format("{0}\n{1}:{2}",
message, ex.GetType().ToString(), ex.Message));
}
public OleDbConnection Connection
{
get
{
return _connection;
}
set
{
//Disconnect
Disconnect();
//Set
_connection = value;
}
}
public void Disconnect()
{
//Do we have a conncetion?
if(_connection !=null)
{
//Is it open?
if (_connection.State != ConnectionState.Closed)
_connection.Close();

//Clear it...
_connection = null;
}
}
private void menuDataLoad_Click(object sender, EventArgs e)
{
LoadData();
}
public void LoadData()
{
// Do we have a connection?
if (null == _connection)
{
MessageBox.Show(this, "You must connect to a database.");
return;
}
//Setup..
try
{
//Create a dataset....
DataSet dataset = new DataSet();
//Create and fill the tables.....
DataTable customers = CreateAndFill(dataset, "Customers");
DataTable orders = CreateAndFill(dataset, "Orders");
// DataTable orderDetails = CreateAndFill(dataset, "Order Details");
DataTable orderDetails = CreateAndFill(dataset, "Order Details Extended");
//Establish customers /orders relationship.....
DataRelation customersToOrders =
new DataRelation("OrdersForCustomers",
customers.Columns["CustomerID"],
orders.Columns["CustomerID"]);
dataset.Relations.Add(customersToOrders);


//Establish orders /order details relationship....
DataRelation ordersToOrderDetails =
new DataRelation("OrderDetailsForOrder",
orders.Columns["OrderID"],
orderDetails.Columns["OrderID"]);
dataset.Relations.Add(ordersToOrderDetails);
//show the dataset.....
datagridCustomers.DataSource = dataset;
datagridCustomers.DataMember = customers.TableName;
}
catch (Exception ex)
{
//report the problem...
HandleException("The data could not be loaded.", ex);
}
}
protected DataTable CreateAndFill(DataSet dataset, string tableName)
{
//Create the new table...
DataTable table = new DataTable(tableName);
//add it to the dataset....
dataset.Tables.Add(table);
//Fill the table..
Fill(table);
// Retrun the table....
return table;
}
protected void Fill(DataTable table)
{
//set up command and adapter....
OleDbCommand command = null;
OleDbDataAdapter adapter = null;

try
{
command = Connection.CreateCommand();
command.CommandText = table.TableName;
command.CommandType = CommandType.TableDirect;
adapter = new OleDbDataAdapter(command);
adapter.Fill(table);
}
finally
{
if (adapter != null)
adapter.Dispose();
if (command != null)
command.Dispose();
}
}

private void menuDataSaveChanges_Click(object sender, EventArgs e)
{
SaveChanges();
}
public void SaveChanges()
{
if (null==_connection )
{
MessageBox.Show("You must connect to a database.");
return;
}
DataSet dataset = (DataSet)datagridCustomers.DataSource;
if (null == dataset)
{
MessageBox.Show("You must load a DataSet.");
return;
}
OleDbCommand command = null;
OleDbDataAdapter adapter = null;
try
{
command = _connection.CreateCommand();
command.CommandText = "Customers";
command.CommandType = CommandType.TableDirect;
adapter = new OleDbDataAdapter(command);
OleDbCommandBuilder builder = new OleDbCommandBuilder(adapter);
adapter.Update(dataset.Tables ["Customers"]);
MessageBox.Show("Changes have been saved.");
}
finally
{
//Claan up.....
if (null != adapter)
adapter.Dispose();
if (null != command)
command.Dispose();
}

}
}
}
[解决办法]

C# code
            string source =Application .StartupPath + "\\data\\photo.mdb";            string sqlconn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + source;            string sql = "SELECT * FROM photo";            OleDbCommand oldcom = new OleDbCommand(sql, new OleDbConnection(sqlconn));            OleDbDataAdapter oleda = new OleDbDataAdapter(oldcom);            DataSet ds = new DataSet();            oleda.Fill(ds, "photo");            this.dataGridView1.DataSource = ds.Tables["photo"].DefaultView; 


[解决办法]
。。MSDN不是很详细吗?

下面的示例将 OleDbCommand 和 OleDbDataAdapter 以及 OleDbConnection 一起使用,从 Access 数据库中选择行。然后返回已填充的 DataSet。向该示例传递一个已初始化的 DataSet、一个连接字符串、一个查询字符串(它是一个 SQL SELECT 语句)和一个表示源数据库表的名称的字符串。


C# code
public void ReadMyData(string connectionString){    string queryString = "SELECT OrderID, CustomerID FROM Orders";    using (OleDbConnection connection = new OleDbConnection(connectionString))    {        OleDbCommand command = new OleDbCommand(queryString, connection);        connection.Open();        OleDbDataReader reader = command.ExecuteReader();        while (reader.Read())        {            Console.WriteLine(reader.GetInt32(0) + ", " + reader.GetString(1));        }        // always call Close when done reading.        reader.Close();    }}
[解决办法]
C# code
            //添加一行            OleDbConnection dconn= new OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + Application.StartupPath + @"\data\photo.mdb");            dconn.Open();            OleDbCommand dcomm = new OleDbCommand("insert into photo (photoid,photo) values(@id,@photo)", dconn);            dcomm.Parameters.AddWithValue("@ID", "0008");            dcomm.Parameters.AddWithValue("@PHOTO", DBNull.Value);            dcomm.ExecuteNonQuery(); 

读书人网 >C#

热点推荐