C# tutorial-Database support: Connection object |
|||||||||||||||||||||||||||
C# Database Access with ADO.NET
Connection Connection ObjectWhen you want to connect to a database, you will use the Connection object. In this part you will learn to connect to databases of Ms. Access and SQL Server. To connect to Ms. Access databases, we use System.Data.Oledb class. And to connect to SQL Server databases, we use System.Data.SqlClient class.
Example: Connect to Ms. Access database OleDbConnection cn; //Create Connection object
cn = new OleDbConnection("Provider=Microsoft.Jet.Oledb.4.0; Data Source=" + Application.StartupPath + "\\dbimages.mdb"); 'Open Connection to the database cn.Open(); OR //Create Connection object OleDbConnection cn=new OleDbConnection(); //Set connection string cn.ConnectionString="Provider=Microsoft.Jet.Oledb.4.0; Data Source="+ Application.StartupPath+ "\\dbimages.mdb";cn.Open();
This code will connect to Ms. Access database “dbimages.mdb” located in start up path of the current project. The database contains a table named tblimages that store image ID and its path.
Example: Connect to SQL Server database
SqlConnection cn; //Create Connection object cn = new SqlConnection("Server=(local); Database=dbimages; User=sa; Password=123;"); //Open connection cn.Open();
OR //Create Connection object SqlConnection cn=new SqlConnection(); //Set connection string cn.ConnectionString="Server=(local); Database=dbimages; User=sa; Password=123;" //Open connection cn.Open();
This code will connect to SQL Server database “dbimages” in the local machine.
|
|||||||||||||||||||||||||||
|
|||||||||||||||||||||||||||