This tutorial will show you how you can connect to MS SQL server using ASP.Net C#.
First of all, you will need to import the SqlClient namespace into your project or site page.
//required sql namespace using System.Data.SqlClient;
The following quick function will connect to the MS SQL server. Basically it defines the SqlConnection object and attaches a connection string value into the object. The .Open() method will try to connect to the server and .Close() method basically will close the database connection.
//private function for testing connection private void ConnectToSQL() { string connectionString = @"Data Source=\SQLEXPRESS;Initial Catalog=DBNAME_HERE;User ID=USERNAME_HERE;Password=PASSWORD_HERE"; using (SqlConnection objSqlConnection = new SqlConnection(connectionString)) { try { objSqlConnection.Open(); objSqlConnection.Close(); Response.Write("Connection is successfull"); } catch (Exception ex) { Response.Write("Error : " + ex.Message.ToString()); } } }
To test it, you can call the function in the Page_Load method just to see what will happen. Remember to set the connectionstring correctly according to your setting.