在C#中实现Access数据库的多用户访问控制,可以通过以下几个步骤来完成:
using System;
using System.Data;
using System.Data.OleDb;
private OleDbConnection ConnectToAccessDatabase(string databasePath)
{
string connectionString = $"Provider=Microsoft.ACE.OLEDB.12.0;Data Source={databasePath};Persist Security Info=False;";
OleDbConnection connection = new OleDbConnection(connectionString);
connection.Open();
return connection;
}
private DataTable ExecuteQuery(OleDbConnection connection, string query)
{
OleDbCommand command = new OleDbCommand(query, connection);
OleDbDataAdapter adapter = new OleDbDataAdapter(command);
DataTable result = new DataTable();
adapter.Fill(result);
return result;
}
public void AccessControl(string databasePath, string username, string password)
{
using (OleDbConnection connection = ConnectToAccessDatabase(databasePath))
{
// 检查用户是否存在
string checkUserQuery = $"SELECT COUNT(*) FROM Users WHERE Username = '{username}' AND Password = '{password}'";
DataTable userResult = ExecuteQuery(connection, checkUserQuery);
if (userResult.Rows[0][0] != DBNull.Value && (int)userResult.Rows[0][0] > 0)
{
Console.WriteLine("用户验证成功,欢迎使用!");
// 在此处添加你的业务逻辑代码
}
else
{
Console.WriteLine("用户名或密码错误,请重新输入!");
}
}
}
AccessControl
方法:public static void Main(string[] args)
{
string databasePath = @"C:\path\to\your\database.accdb";
string username = "your_username";
string password = "your_password";
AccessControl(databasePath, username, password);
}
这样,你就可以实现一个简单的Access数据库多用户访问控制。请注意,这个示例仅用于演示目的,实际应用中需要考虑更多的安全性和性能优化。