C#连接ACCESS数据库增删改查
时间: 2024-05-30 19:05:05 浏览: 118
c#数据库的增删改查
C#连接ACCESS数据库进行增删改查操作可以通过ADO.NET来实现。下面是一个简单的示例代码:
1. 首先,需要引入System.Data.OleDb命名空间。
2. 连接数据库:
```csharp
string connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=path_to_your_database.accdb";
OleDbConnection connection = new OleDbConnection(connectionString);
connection.Open();
```
3. 执行查询操作:
```csharp
string query = "SELECT * FROM TableName";
OleDbCommand command = new OleDbCommand(query, connection);
OleDbDataReader reader = command.ExecuteReader();
while (reader.Read())
{
// 处理查询结果
}
reader.Close();
```
4. 执行插入操作:
```csharp
string insertQuery = "INSERT INTO TableName (Column1, Column2) VALUES (@Value1, @Value2)";
OleDbCommand insertCommand = new OleDbCommand(insertQuery, connection);
insertCommand.Parameters.AddWithValue("@Value1", value1);
insertCommand.Parameters.AddWithValue("@Value2", value2);
insertCommand.ExecuteNonQuery();
```
5. 执行更新操作:
```csharp
string updateQuery = "UPDATE TableName SET Column1 = @Value1 WHERE Column2 = @Value2";
OleDbCommand updateCommand = new OleDbCommand(updateQuery, connection);
updateCommand.Parameters.AddWithValue("@Value1", newValue1);
updateCommand.Parameters.AddWithValue("@Value2", conditionValue);
updateCommand.ExecuteNonQuery();
```
6. 执行删除操作:
```csharp
string deleteQuery = "DELETE FROM TableName WHERE Column = @Value";
OleDbCommand deleteCommand = new OleDbCommand(deleteQuery, connection);
deleteCommand.Parameters.AddWithValue("@Value", value);
deleteCommand.ExecuteNonQuery();
```
7. 关闭数据库连接:
```csharp
connection.Close();
```
阅读全文