在C#中使用OleDbConnection進行數據備份和恢復操作需要使用SQL語句來實現。以下是一個簡單的示例代碼:
using System;
using System.Data.OleDb;
namespace DataBackupRestore
{
class Program
{
static void Main(string[] args)
{
string connectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\\data\\database.mdb";
// 備份數據
using (OleDbConnection connection = new OleDbConnection(connectionString))
{
connection.Open();
string backupPath = "C:\\data\\backup.mdb";
string backupQuery = $"SELECT * INTO [MS Access;Database={backupPath}].* FROM TableName;";
using (OleDbCommand command = new OleDbCommand(backupQuery, connection))
{
command.ExecuteNonQuery();
}
}
// 恢復數據
using (OleDbConnection connection = new OleDbConnection(connectionString))
{
connection.Open();
string restorePath = "C:\\data\\restore.mdb";
string restoreQuery = $"SELECT * INTO TableName FROM [MS Access;Database={restorePath}].TableName;";
using (OleDbCommand command = new OleDbCommand(restoreQuery, connection))
{
command.ExecuteNonQuery();
}
}
}
}
}
在上面的示例中,首先連接到數據庫,然后使用SELECT INTO語句將數據備份到指定路徑的數據庫文件中。然后再次連接到原始數據庫,使用SELECT INTO語句從備份文件中恢復數據。請確保替換示例代碼中的數據庫路徑和表名為實際需要備份和恢復的數據庫和表名。