Sunday, August 30, 2009

Database Connectivity in C#

DBMS Connectivity

Connect with an Oracle Database

Add the following Reference:
“System.Data.OracleClient” // Help is given at the end on how to add a reference

On top of the page, write down:
using System.Data.OracleClient;

To execute “select” type queries, use the following code:

DataSet ds = new DataSet();
OracleDataAdapter da = new OracleDataAdapter(“QUERY”,@”Connection String”);
Da.Fill(ds,”abc”);
// Query Strings are given at the end

dataGridView1.DataSource = ds.Tables[“abc”]; // dataGridView1 is the name of the data grid where we display the result of the query

To execute “insert” type queries, use the following code:

OracleConnection con = new OracleConnection(@”Connection String”);
OracleCommand cmd = new OracleCommand(“QUERY”,con);
Con.Open();
cmd.ExecuteNonQuery();
con.Close();



Connect with a MySQL Database

For MySQL, replace the keyword ‘Oracle’ by ‘MySQL’ in all these statements, and perform the following additions:

Add the following reference:
“MySql.Data” from the dll file attached, which is “MySQL.Data.dll”
On top of the page write down:
Using MySql.Data.MySqlClient;

The remaining code will be the same as stated above.

Connection Strings

Connection String for Oracle
Server=localhost;Data Source=nameofdatasource;User Id=username;Password=password;
Connection String for MySQL
Server=localhost;Database=nameofdatasource;Uid=username;Pwd=password;


Adding a Reference
On the top right of the page there is a Solution Explorer
In the solution explorer, there is a folder named References.
Right click on References and click “Add Reference”
Scroll Down, select your reference and click OK

No comments:

Post a Comment