C# 使用两个参数查询 Access 数据库并筛选数据
假设有一个 Access 数据库,其中有一个表格叫做'Students',包含以下字段:
- ID (自动编号)
- Name (文本类型)
- Age (数字类型)
- Gender (文本类型)
我们要查询出年龄在某个范围内的男性学生,可以使用以下代码:
using System.Data.OleDb;
...
int minAge = 18;
int maxAge = 25;
string connectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Path\To\Database.mdb";
string query = "SELECT * FROM Students WHERE Age >= ? AND Age <= ? AND Gender = 'Male'";
using (OleDbConnection connection = new OleDbConnection(connectionString))
{
OleDbCommand command = new OleDbCommand(query, connection);
command.Parameters.AddWithValue("@p1", minAge);
command.Parameters.AddWithValue("@p2", maxAge);
connection.Open();
OleDbDataReader reader = command.ExecuteReader();
while (reader.Read())
{
int id = reader.GetInt32(0);
string name = reader.GetString(1);
int age = reader.GetInt32(2);
string gender = reader.GetString(3);
Console.WriteLine("{0}, {1}, {2}, {3}", id, name, age, gender);
}
reader.Close();
}
解释一下这段代码:
- 首先定义了最小年龄和最大年龄两个变量。
- 然后定义了连接字符串和查询语句。注意到查询语句中使用了两个参数占位符 '?' 和一个固定的字符串 'Male'。
- 创建 OleDbConnection 和 OleDbCommand 对象,并将查询语句和参数传入 OleDbCommand 对象。
- 使用 OleDbCommand.Parameters.AddWithValue 方法为参数设置值。注意到参数的名称 '@p1' 和 '@p2' 与查询语句中的占位符一一对应。
- 打开数据库连接并执行查询。使用 OleDbDataReader 对象读取查询结果,并输出每个学生的信息。
- 最后关闭 OleDbDataReader 和 OleDbConnection 对象。
这样就可以查询出符合条件的学生信息了。
原文地址: https://www.cveoy.top/t/topic/owl5 著作权归作者所有。请勿转载和采集!