如果要使用Windows身份验证来连接到SQL Server数据库,可以使用以下代码示例:
//在Web.config文件中添加数据库连接字符串
//在代码中获取数据库连接对象 using System.Data.SqlClient;
SqlConnection connection = new SqlConnection(); connection.ConnectionString = ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString; connection.Open();
...
//执行SQL命令 SqlCommand command = new SqlCommand("SELECT * FROM MyTable", connection); SqlDataReader reader = command.ExecuteReader();
while (reader.Read()) { //读取数据 }
//关闭连接 connection.Close();