Wednesday, October 23, 2013

Simple SQL connection

Hi everyone,
In a case you need to create fast and simple SQL connection and get some data from it, there is a nice solution for you :) I won't discuss whether it is appropriate approach or not. This is just about to get your data in fast way without hassling about connection strings or web. configs. So please keep that in mind when you use it ;)

string Server = "<yourServer.com>";
string DB = "<yourDatabaseName>";
string connectionString = "Data Source=" + Server + ";Initial Catalog=" + DB + ";user id=<username>;password=<userPassword>";
DataTable dataTable = new DataTable();

using (SqlConnection conn = new SqlConnection(connectionString))
{
    //Open connection
    conn.Open();

     //Set SQLCommand
     using (SqlCommand cmd = new SqlCommand(<YourSQLcommand>, conn))
                    {
                        using (SqlDataAdapter sqlDataAdapter = new SqlDataAdapter())
                        {
                            //Use SQL Command
                            sqlDataAdapter.SelectCommand = cmd;
                            try
                            {
                                //Fill DataTable
                                sqlDataAdapter.Fill(dataTable);
                            }
                            catch (Exception ex)
                            {
                                <handle errors here>
                            }
                        }
                    }
}
This is it.. hope it helps ;)

No comments:

Post a Comment