Thursday, April 9, 2009

Connect to MS SQL database from C#

Step 1: Set connection string
string connectionString = "user id=" + your_user_id + ";" +
"password=" + your_password + ";" +
"server=" + server + ";" +
"Trusted_Connection=" + "yes" + ";" +
"database=" + database_name + "; " +
"connection timeout=" + "30" ;

'''the server name is your comuputer name\\SQL Server name
'''e.g. abccomputer\\SQLEXPRESS


Step 2: Connect using the connection string and open the connection
SqlConnection connection;
connection = new SqlConnection(connectionString);
connection.Open();


Step 3: Execute SqlCommand and Read output
string query = "SELECT * FROM Table1;";
SqlCommand sqlCommand1 = new SqlCommand(query, connection);
SqlDataReader dataReader = mSqlCommand.ExecuteReader();

Step 4: Read the output
string result = "";while (dataReader.Read())
{
result += mSqlDataReader["column1"];
result += mSqlDataReader["column2"];
result += mSqlDataReader["column3"];
result += Environment.NewLine;
}
MessageBox.Show(result);


Step 5: Close the connection

connection.Close();

Don't forget to add this line "using System.Data.SqlClient;" at the top of your program