Connecting to MSSQL Server in ASP.NET

Discussion in 'ASP.NET' started by pradeep, Jan 15, 2007.

  1. pradeep

    pradeep Team Leader

    Joined:
    Apr 4, 2005
    Messages:
    1,645
    Likes Received:
    87
    Trophy Points:
    0
    Occupation:
    Programmer
    Location:
    Kolkata, India
    Home Page:
    http://blog.pradeep.net.in
    Everything you need comes with the .NET Framework. When you say you are trying to connect to SQL Server, you need to know a bit more than how to create a connection, but also how to return data and display it. Firstly, there are actually many ways to do this in .NET - some in code, some through the IDE and wizards.

    To give your page access to the classes you will need to perform SQL data access, you must import the System.Data and System.Data.SqlClient namespaces into your page or codebehind.

    Code:
      <%@ Import Namespace="System.Data" %>
      <%@ Import Namespace="System.Data.SqlClient" %>
    Connect to the MS SQL server, using the following syntax.

    Code:
      mySqlConnection = new SqlConnection("server=mssql.win-servers.com;user=dbuser;password=dbpwd;database=db")
      mySqlCommand = new SqlCommand("SELECT * FROM test", mySqlConnection)
      mySqlConnection.Open()
    Full Example below.

    Code:
    <%@ Page Language="VB" Debug="true" %>
      <%@ Import Namespace="System.Data" %>
      <%@ Import Namespace="System.Data.SqlClient" %>
      <html>
     <title>Test</title></head>
     
      <body>
      <%
      Dim myDataReader as SqlDataReader
      Dim mySqlConnection as SqlConnection
      Dim mySqlCommand as SqlCommand
      
      
      mySqlConnection = new SqlConnection("server=mssql.win-servers.com;user=dbuser;password=dbpwd;database=db")
      mySqlCommand = new SqlCommand("SELECT * FROM test", mySqlConnection)
      mySqlConnection.Open()
      myDataReader = mySqlCommand.ExecuteReader(CommandBehavior.CloseConnection)
          
      
      Do While (myDataReader.Read())
          Response.Write(myDataReader.getDecimal(0))
          Response.Write(myDataReader.getString(1) )
          Response.Write("<br/>")
      Loop
           
      ' Always call Close when done reading.
      myDataReader.Close()
      
      ' Close the connection when done with it.
      mySqlConnection.Close()  
      %>
     
  2. Mr Download

    Mr Download New Member

    Joined:
    Sep 1, 2008
    Messages:
    1
    Likes Received:
    0
    Trophy Points:
    0

Share This Page

  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice