是的,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 實例,分別使用不同的連接字符串連接到兩個不同的數據庫。然后我們分別執行查詢并打印結果。