使用ADO.NET来编写Access数据库的增删改查代码
时间: 2024-03-28 13:41:27 浏览: 87
使用ADO.NET来编写Access数据库的增删改查代码,可以分为以下几个步骤:
1. 建立数据库连接:
```
string connectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\mydatabase.mdb;";
OleDbConnection conn = new OleDbConnection(connectionString);
conn.Open();
```
2. 增加数据:
```
string query = "INSERT INTO mytable (name, age) VALUES (?, ?)";
OleDbCommand cmd = new OleDbCommand(query, conn);
cmd.Parameters.AddWithValue("@name", "John");
cmd.Parameters.AddWithValue("@age", 30);
cmd.ExecuteNonQuery();
```
3. 删除数据:
```
string query = "DELETE FROM mytable WHERE id = ?";
OleDbCommand cmd = new OleDbCommand(query, conn);
cmd.Parameters.AddWithValue("@id", 1);
cmd.ExecuteNonQuery();
```
4. 变更数据:
```
string query = "UPDATE mytable SET name = ? WHERE id = ?";
OleDbCommand cmd = new OleDbCommand(query, conn);
cmd.Parameters.AddWithValue("@name", "Mike");
cmd.Parameters.AddWithValue("@id", 2);
cmd.ExecuteNonQuery();
```
5. 查询数据:
```
string query = "SELECT * FROM mytable";
OleDbCommand cmd = new OleDbCommand(query, conn);
OleDbDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
Console.WriteLine("Name: " + reader["name"] + ", Age: " + reader["age"]);
}
reader.Close();
```
注意:以上代码中,使用了参数化查询来防止SQL注入攻击。此外,还需要在程序结束时关闭数据库连接。
阅读全文