access数据库增删改查
时间: 2023-11-22 11:49:14 浏览: 77
以下是C#对Access数据库的增删改查操作的示例代码:
1.连接Access数据库
```csharp
using System.Data.OleDb;
string connStr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=yourDatabase.mdb";
OleDbConnection conn = new OleDbConnection(connStr);
conn.Open();
```
2.查询数据
```csharp
string sql = "SELECT * FROM yourTable";
OleDbCommand cmd = new OleDbCommand(sql, conn);
OleDbDataReader reader = cmd.ExecuteReader();while (reader.Read())
{
Console.WriteLine(reader["columnName"].ToString());
}
reader.Close();
```
3.插入数据
```csharp
string sql = "INSERT INTO yourTable (columnName1, columnName2) VALUES (@value1, @value2)";
OleDbCommand cmd = new OleDbCommand(sql, conn);
cmd.Parameters.AddWithValue("@value1", "yourValue1");
cmd.Parameters.AddWithValue("@value2", "yourValue2");
cmd.ExecuteNonQuery();
```
4.更新数据
```csharp
string sql = "UPDATE yourTable SET columnName1=@value1 WHERE columnName2=@value2";
OleDbCommand cmd = new OleDbCommand(sql, conn);
cmd.Parameters.AddWithValue("@value1", "yourNewValue1");
cmd.Parameters.AddWithValue("@value2", "yourValue2");
cmd.ExecuteNonQuery();
```
5.删除数据
```csharp
string sql = "DELETE FROM yourTable WHERE columnName=@value";
OleDbCommand cmd = new OleDbCommand(sql, conn);
cmd.Parameters.AddWithValue("@value", "yourValue");
cmd.ExecuteNonQuery();
```
阅读全文