Thursday, 22 March 2012

How to Connect Database from C# with Asp.net


ADO or ADO.Net utilize a provider to do the job for you. The connection string contains the information that the provider needs to know to be able to establish a connection to the database or the data file.   Because there are different providers and each providers have multiple ways to make a connection there are many different ways to write a connection string. It's like the address when sending a regular mail. Depending on the origin and destination and who is going to make the transport you need to write down the address in different ways.  For example; the provider needs the address to the server (or the path to the data file) to connect to. This parameter is often named "Server" or "Data Source". The value specified for this key in the connection string is passed on to the provider and this is how it’s possible for the provider to know where to connect.
A connection string provides the information that a provider needs to communicate with a particular database. You can store connection strings in the Web.config file and reference the configuration entries in data source controls.
Depending on the provider, a connection string usually supplies the server or location of the database server, the particular database to use, and authentication information. As with the provider, you can indicate the connection string within the Web.config file or as a property of an individual data source control on a page.
Connection String Storage Area
It is good practice to place connection strings in the Web.config file. Within the <Configuration> element, you can create a child element named <connectionStrings> and place your connection strings there, as shown in this example:
Example of Sql Server2008,Mysql Database connection string:

<appSettings>
<add key="ConnectionString“value="server=ServerName; userid=UserId; Password=Password; database=DatabaseName; persist security info=False"/>
</appSettings>

Example of OLEDB Database connection string:
<appSettings>
    <add key="ConnectionString" value="Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\\AccessDB\\xxxx.mdb;Persist Security Info=False;Jet OLEDB:Database Password=Password " />
  </appSettings>

Connection string in C#
Mysql Connection string :Before writing connection string include spcify names for your database(Mysql,sql….) ,and also include configuration namespace.

Ex:
using MySql.Data.MySqlClient;
using System.Configuration;

MySqlConnectioncon=new MySqlConnection(ConfigurationManager.AppSettings["ConnectionString"].ToString());

 

No comments:

Post a Comment