Welcome to Sudeep Pandey

Just for sharing ideas and knowledge— My Blog

Connection String

There are different ways of connecting database to .NET. Here, I am discussing with SQL Server.

1) Windows Authentication:
Windows Authentication is a trusted connection. Here is the simple string defined for connection string.
string connString= @”Data Source=SUDEEP-PANDEY\SQLEXPRESS;Initial Catalog=customer;Integrated Security=SSPI”;
In this example,
Data Source means the source connecting to data.
Initial Catalog means the database
Integrated Security is for windows authentication

The below is the simple that demonstrate to connect,
string connString = @”Data Source=SUDEEP-PANDEY\SQLEXPRESS;Initial Catalog=customer;Integrated Security=SSPI”;
SqlConnection conn = new SqlConnection(connString);
try
{
conn.Open();
Label1.Text = “Connection is passed”;
}
catch(Exception ex)
{
Label1.Text=ex.Message;
}

We can also define the connection string in xml file(web.config):

<connectionStrings>
<add name=”ADOExmServer” connectionString=”Data Source=SUDEEP-PANDEY\SQLEXPRESS;Initial Catalog=customer;Integrated Security=SSPI”/>
<add name=”ADOExmServer1″ connectionString=”Data Source=SUDEEP-PANDEY\SQLEXPRESS;Initial Catalog=HRM;Integrated Security=SSPI”/>
</connectionStrings>

In the above connection, we have connect to two database: customer and HRM

To access this connection string in C#, we do,
string connString = ConfigurationManager.ConnectionStrings["ADOExmServer"].ConnectionString;
SqlConnection conn = new SqlConnection(connString);

2)SQL Server Authentication
Before going to SQL Server Authentication, we have to understand user and its role. We have to create user for sql server. To create the user we have to go through the windows authentication.
Some time database has no authorization. Please follow this link:
http://sqlmusings.wordpress.com/2008/06/12/issue-server-principal-is-not-able-to-access-the-database-under-the-current-security-context/

Connection string for sql server authentication is given by:
<add name=”ADOExmServer1″ connectionString=”Data Source=SUDEEP-PANDEY\SQLEXPRESS;
Initial Catalog=customer;uid=interview;password=test123″/>

Leave a Reply

You must be logged in to post a comment.