| Different way to connect C# with Database Servers. |
| C# Connection string to connect Sql
Server with Windows Authentication |
|
|
|
string connectionstring ="data source=[Servername];initial catalog=Northwind;
integrated security=SSPI;persist security info=False; Trusted_Connection=Yes."
Where datasource will be computer name or IP Address, and
initial catalog is the name of database.
If you’re using SQL Server 2005 Express Edition, your connection string will
include an instance name, as shown here: SqlConnection myConnection = new
SqlConnection();
myConnection.ConnectionString = @"Data Source=localhost\SQLEXPRESS;" + "Initial
Catalog=Pubs;Integrated Security=SSPI";
|
| C# Connection string to connect SQL Server through OLE DB
Provider with Windows Authentication |
Here’s an example that uses a connection string to connect to SQL Server
through the OLE DB provider:
OleDbConnection myConnection = new OleDbConnection();
myConnection.ConnectionString = "Provider=SQLOLEDB.1;Data Source=localhost;" +
"Initial Catalog=Pubs;Integrated Security=SSPI"; |
| What is best way to store connection string and Retrieve the
connection string |
Storing the Connection String Typically, all the database code in your
application will use the same connection string. For that reason, it usually
makes the most sense to store a connection string in a class member variable
or, even better, a configuration file. You can also create a Connection object
and supply the connection string in one step by using a dedicated constructor:
SqlConnection myConnection = new SqlConnection(connectionString);
// myConnection.ConnectionString is now set to connectionString. You don’t need
to hard-code a connection string. The < connectioString >section of
the web.config file is a handy place to store your connection strings. Here’s
an example
< configuration >
< connectionStrings >
<add name="Pubs" connectionString="Data Source=localhost;Initial
Catalog=Pubs;Integrated Security=SSPI" / >
< / connectionStrings>
...
< /configuration >
You can then retrieve your connection string by name. First, import the
System.Web.Configuration namespace. Then, you can use code like this:
string connectionString =
WebConfigurationManager.ConnectionStrings["Pubs"].ConnectionString;
|