是的,C# SQLHelper 可以连接多个数据库。要实现这个功能,您需要为每个数据库创建一个单独的连接字符串,并在创建 SqlHelper 实例时使用相应的连接字符串。以下是一个简单的示例:
using System;
using System.Data;
using System.Data.SqlClient;
public class SQLHelper
{
private string _connectionString;
public SQLHelper(string connectionString)
{
_connectionString = connectionString;
}
public DataTable ExecuteQuery(string query)
{
using (SqlConnection connection = new SqlConnection(_connectionString))
{
connection.Open();
using (SqlCommand command = new SqlCommand(query, connection))
{
using (SqlDataReader reader = command.ExecuteReader())
{
DataTable result = new DataTable();
result.Load(reader);
return result;
}
}
}
}
}
class Program
{
static void Main(string[] args)
{
string connectionString1 = "Server=Server1;Database=Database1;User Id=User1;Password=Password1;";
string connectionString2 = "Server=Server2;Database=Database2;User Id=User2;Password=Password2;";
SQLHelper sqlHelper1 = new SQLHelper(connectionString1);
SQLHelper sqlHelper2 = new SQLHelper(connectionString2);
DataTable result1 = sqlHelper1.ExecuteQuery("SELECT * FROM Table1");
DataTable result2 = sqlHelper2.ExecuteQuery("SELECT * FROM Table2");
Console.WriteLine("Result from Database1:");
result1.Print();
Console.WriteLine("\nResult from Database2:");
result2.Print();
}
}
在这个示例中,我们创建了两个 SQLHelper 实例,分别使用不同的连接字符串连接到两个不同的数据库。然后我们分别执行查询并打印结果。