Example : How to Connect C# with Sql Server database in Asp .net .
//using System.Data.OracleClient;
//using System.Data.OleDb;
//using System.Data.Odbc;
using System.Data.SqlClient;

---------------------------------------------------------------------------------------
protected void Page_Load(object sender, EventArgs e)
  {  
 
 //First method of Connectivity code(For External SQL Server Database .dbo File)

        String cs;
        SqlConnection conn;
        cs = @"Data Source=DESKTOP-MT31ONS;Initial Catalog=SITEDB;User ID="";Password=""; Integrated Security=True";
        conn = new SqlConnection(cs);

        conn.Open();
        Response.Write("Database Connected");
        conn.Close();



//Another method of Connectivity code(For External SQL Server Database .dbo file)

        
   String cs = "data source =.; database= SITEDB; integrated security=SSPI";  //Another Connectivity code
   SqlConnection conn = new SqlConnection(cs);

   Response.Write("Database connected successfully......!"); 
 

//Another method of Connectivity code(For Internal SQL Server Database .mdf file)

   SqlConnection conn = new SqlConnection(@"Data Source=(LocalDB)\MSSQLLocalDB; AttachedDbFilename Initial Catelog=SITEDB; Integrated Security=True;");
                                               OR

SqlConnection conn = new SqlConnection(@"Data Source=(LocalDB)\MSSQLLocalDB; AttachedDbFilename=c:\data\App_Data\
SITEDB.mdf;Integrated Security=True;");


      Response.Write("Database connected successfully......!");
        
        //SqlConnection con;
        //SqlDataAdapter da;
        //DataTable dt = new DataTable();
        //DataRow dr;

   } 

NB : (i) Here SITEDB is the Database Name, DESKTOP-MT31ONS is Server Name and rest is keyword. 

(ii) Step to create Internal SQL Server Database file already present in visual studio (without installing SQL Server application) = Open Web application first - Click on WEBSITE menu - click Add New Item - choose SQL Server Database file from the appeared window - put the suitable database name - Add - Database added in the Server Explorer - now we can create table here to store and display data. 
   
        

Loading

Categories: ASP .Net

0 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.