使用c#开发一个可以批量备份sqlserver数据库的工具
以下是一个简单的C#代码示例,可用于批量备份SQL Server数据库:
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.IO;
namespace SQLServerBackupTool
{
class Program
{
static void Main(string[] args)
{
string serverName = "localhost\\SQLEXPRESS"; // SQL Server实例名
string databaseName = "TestDB"; // 要备份的数据库名
string backupFolder = @"C:\SQLBackups\"; // 备份文件存储目录
// 获取数据库连接字符串
string connectionString = $"Server={serverName};Database={databaseName};Trusted_Connection=True;";
// 创建一个SqlConnection对象
using (SqlConnection connection = new SqlConnection(connectionString))
{
// 打开连接
connection.Open();
// 获取所有表名
List<string> tableNames = GetTableNames(connection);
// 备份每张表
foreach (string tableName in tableNames)
{
BackupTable(connection, tableName, backupFolder);
}
// 关闭连接
connection.Close();
}
}
// 获取数据库中所有表的名称
static List<string> GetTableNames(SqlConnection connection)
{
List<string> tableNames = new List<string>();
// 构造一个SqlCommand对象
SqlCommand command = new SqlCommand("SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE='BASE TABLE'", connection);
// 执行查询并读取结果
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
tableNames.Add(reader.GetString(0));
}
}
return tableNames;
}
// 备份一张表
static void BackupTable(SqlConnection connection, string tableName, string backupFolder)
{
// 构造一个SqlCommand对象
SqlCommand command = new SqlCommand($"SELECT * FROM {tableName}", connection);
// 执行查询并读取结果
using (SqlDataReader reader = command.ExecuteReader())
{
// 构造一个StreamWriter对象,用于写入备份文件
StreamWriter writer = new StreamWriter(Path.Combine(backupFolder, tableName + ".csv"), false);
// 写入表头
for (int i = 0; i < reader.FieldCount; i++)
{
writer.Write($"{reader.GetName(i)},");
}
writer.WriteLine();
// 写入每行数据
while (reader.Read())
{
for (int i = 0; i < reader.FieldCount; i++)
{
writer.Write($"{reader.GetValue(i)},");
}
writer.WriteLine();
}
// 关闭StreamWriter
writer.Close();
}
}
}
}
本示例将每张表备份为CSV文件,但你也可以将其备份为其他格式,如SQL文件或二进制文件。同时,请注意在备份数据库之前要确保备份文件存储目录存在,并且当前用户有写入权限。
原文地址: http://www.cveoy.top/t/topic/LSg 著作权归作者所有。请勿转载和采集!