在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數據庫多用戶訪問控制。請注意,這個示例僅用于演示目的,實際應用中需要考慮更多的安全性和性能優化。