在C#中,你可以使用System.Data.SqlClient命名空间中的SqlConnection类来连接SQL Server数据库。下面是一个简单的示例:
using System;using System.Data.SqlClient;class Program{static void Main(){// 设置数据库连接字符串string connectionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password";// 创建一个SqlConnection对象using (SqlConnection connection = new SqlConnection(connectionString)){try{// 打开数据库连接connection.Open();Console.WriteLine("成功连接到数据库!");}catch (SqlException ex){Console.WriteLine("连接数据库出错:" + ex.Message);}finally{// 关闭数据库连接connection.Close();}}}}你需要替换示例代码中的ServerName、DatabaseName、UserName和Password为你要连接的SQL Server实例的具体信息。在try块中,我们使用Open()方法打开数据库连接,在catch块中捕获并处理任何可能出现的异常,在finally块中使用Close()方法关闭数据库连接。

