| [Home] | ADO .NET | ||
//********************************************************/
// Description: basic usage of ADO .NET
//********************************************************/
//
//1. From the File select New -> Project.
//2. Select template C# -> Console Application.
//3. Name project as Test1.
//4. Insert the following code.
//********************************************************/
using System;
using System.Data.OleDb;
class CTest1
{
static void Main(string[] args)
{
//connection to database server:
OleDbConnection con = new System.Data.OleDb.OleDbConnection();
//command object instance:
OleDbCommand cmd = new System.Data.OleDb.OleDbCommand();
//connection string:
con.ConnectionString = "Provider=SQLOLEDB.1;Initial Catalog=DB_NAME;Data Source=SERVER_NAME;Workstation ID=SERVER_NAME;User Id=sa;PASSWORD=;";
//connecting...
con.Open();
Console.WriteLine("Connection opened ...");
Console.WriteLine("");
Console.WriteLine("-----------------------");
//indicating to the command object to use a command of type "stored procedure"
cmd.CommandType = System.Data.CommandType.StoredProcedure;
//connection to use:
cmd.Connection = con;
//stored procedure to use:
cmd.CommandText = "storedProcedureName";
//parameter declaration
OleDbParameter prm = cmd.Parameters.Add("@ParameterID", OleDbType.Integer);
prm.Direction = System.Data.ParameterDirection.Input;
//parameter @ParameterID takes value 1
prm.Value = 1;
//DataReader instance
OleDbDataReader dtr;
try
{
//DataReader takes values from the database through the command object
dtr = cmd.ExecuteReader();
Console.WriteLine("-----------------------");
//write to the console the name of the column with index 1:
Console.WriteLine(dtr.GetName(1));
Console.WriteLine("-----------------------");
//read values from DataReader and write them to the console:
while (dtr.Read())
{
//GetString must be replacet with the appropriate method, depending of the type of the data:
Console.WriteLine(dtr.GetString(1));
}
dtr.Close();
dtr = null;
}
//if an error occurs:
catch (System.Data.OleDb.OleDbException e)
{
Console.WriteLine("ERROR!!! {0}", e.Message);
}
//waiting for user to press a key
Console.Read();
con.Close();
con = null;
}
}