Monday, 24 February 2014

how to connect database in c# code project


Connecting the data to database and fetch the records from database and fill the Data adopter; and assign that value to Datatable;


You need to import the SqlConnection and SqlCommand for connecting database to SQl in C#
.
_connection is the variable which is use to make the connection. Where SQLConnection need to implement in C#.

SqlConnection _connection = new SqlConnection(_connectionstring);

Connectionstring is use to pass the connection string, currently we are giving the example of window authentication to the sql server,

 string _connectionstring = @"Data Source=.\SQLEXPRESS;Initial Catalog=Northwind;Integrated Security=True";


SQL command is use to pass the command (or operation) that you want to perform any thing. In current we are trying to read the data from database and maintain it into Datatable.
                SqlCommand _command = new SqlCommand(_sql, _connection);


Full code
protected void btnShow_Click(object sender, EventArgs e)
        {
            BindData();
        }
        private void BindData()
        {
            try
            {
                string _connectionstring = @"Data Source=.\SQLEXPRESS;Initial Catalog=Northwind;Integrated Security=True";
                string _sql = "SELECT * FROM [Orders]";
                SqlConnection _connection = new SqlConnection(_connectionstring);
                SqlCommand _command = new SqlCommand(_sql, _connection);
                SqlDataAdapter _adapter = new SqlDataAdapter(_command);
                DataTable _table = new DataTable();
                _adapter.Fill(_table);
              
            }
            catch
            {
                throw;
            }

        }




In above code using the Datatable to maintain the result getting from the SQlDataAdptor.
SqlDataAdapter  it is using as the bridge for datatable and SQL database. It only convert the data result to datatable. 

It is called and connectionless architecture.


No comments:

Post a Comment