要在C#中連接到SQL Server數據庫,您需要使用ADO.NET提供的類
首先,確保已安裝了System.Data.SqlClient命名空間。如果沒有,請在項目中添加對System.Data.dll的引用。
然后,在代碼中添加以下using指令:
using System.Data;
using System.Data.SqlClient;
public static SqlConnection CreateConnection(string connectionString)
{
SqlConnection connection = new SqlConnection(connectionString);
return connection;
}
string connectionString = "Server=your_server_name;Database=your_database_name;User Id=your_username;Password=your_password;";
SqlConnection connection = CreateConnection(connectionString);
connection.Open();
string query = "SELECT * FROM your_table_name";
SqlCommand command = new SqlCommand(query, connection);
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
Console.WriteLine("Column1: {0}, Column2: {1}", reader[0], reader[1]);
}
connection.Close();
這就是在C#中連接到SQL Server數據庫的基本方法。根據需要,您可以修改此示例以滿足您的特定需求。