Connecting to a Database and Executing a Query


Tutorial about IDbConnection, SqlConnection, OleDbConnection
This tutorial show you how to create a connection to a data source, issue a command, and retrieve the data using typed classes for the SQL Server data provider. To create a connection you use one of  the connection classes that implement SqlConnection and supply a connection string.  To create the connection, you the call Open.
SqlConnection is used to connect Sql Server Database only. 
IDbConnection is a generic interface, OracleConnection, OleDbConnection, SqlConnection all inherits from IDbConnection. 


 If you have multiple database to connect to and of different type, then you can use a factory to create a proper connection type and the you can return IDbConnection instance.

Connection to a Database

To connect to a database you have to define:
  • Connection string for the database
  • Create a Connection object, by using the connection string
  • Invoke the Open method on the Connection Object
SqlConnection cnn = new SqlConnection(); 
string ConnString ="Server=localhost;database=TutorialsCode;"
                    +"Integrated security=SSPI";
cnn.ConnectionString = ConnString;

private void btnConnection_Click(object sender, EventArgs e)
{
    try
   {
      if (cnn.State == ConnectionState.Open)
          cnn.Open();
      MessageBox.Show("Connection was Successful!!");

      if (cnn.State == ConnectionState.Open)
          cnn.Close();

   }
   catch (SqlException ex)     
   {
      MessageBox.Show(ex.Message);
   }

}

Executing a Query

To retrieve data from a database, you must create a command object, initialize it with information about the command, and the execute command. For the SQL Server data provider this is a SqlDataAdapter object. Follow this steps.
  • Connection
  • Query
  • SqlCommand
  • Open Connection
  • ExecuteNonQuery
  • Close Connection

string ConnString ="Server=localhost;database=TutorialsCode;"
                               +"Integrated security=SSPI";
SqlConnection cnn = new SqlConnection(ConnString);

string StringQuery = "select * from TutorialsCode";

SqlCommand CMD = new SqlCommand(StringQuery, cnn);

SqlDataAdapter DA = new SqlDataAdapter(CMD);

cnn.Open();

cmd.ExecuteNonQuery(); 
                           
cnn.Close();




















If you need any help feel free to leave a comment (or) contact me.

No comments:

Post a Comment