IMG-LOGO

How to Connect to Microsoft SQL Server using ASP.Net C#?

andy - 03 Aug, 2013 8931 Views 0 Comment

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.

    
//Sample on how to use it
protected void Page_Load(object sender, EventArgs e) {
    if (!Page.IsPostBack) {
        ConnectToSQL();
    }
}

Comments

There are no comments available.

Write Comment
0 characters entered. Maximum characters allowed are 1000 characters.

Related Articles

How to remove html tags from string in c#?

Sometimes you need to remove HTML tags from string to ensure there are no dangerous or malicious scripts especially when you want to store the string or data text into the database.