Please specify which version of sql server and visual studio are you using because there may be some changes in the coding for different version‘s of visual studio and sql server.For connecting to SQL Server using Windows authentication, perform the following steps: Configure a connection string. Encrypt the connection string, Configure SQL Server security. Test security access.
Code:
<connectionStrings>
<add name="MyDbConn1"
connectionString="Server=MyServer;Database=MyDb;Trusted_Connection=Yes;"/>
<add name="MyDbConn2"
connectionString="Initial Catalog=MyDb;Data Source=MyServer;Integrated Security=SSPI;"/>
</connectionStrings>
The above code ‘s are same. Its optional to encrypt your data . the code works fine without it also To test your asp.net pages , with the connections you made To test database access, create a test ASP.NET Web application and add the following .aspx page.
Code:
<%@ Page Language="C#" %>
<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.SqlClient" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<script runat="server">
protected void Page_Load(object sender, EventArgs e)
{
using (SqlConnection cn = new SqlConnection(ConfigurationManager.ConnectionStrings["MyDbConn1"].ToString()))
{
SqlCommand cmd = new SqlCommand("SELECT COUNT(*) FROM authors", cn);
cn.Open();
SqlDataReader rdr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
rdr.Read();
Response.Write(rdr[0].ToString()); //read a value
}
}
</script>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>SQL Authentication</title>
</head>
<body/>
</html>
Bookmarks