1. We have moved from vBulletin to XenForo and you are viewing the site in the middle of the move. Though the functional aspect of everything is working fine, we are still working on other changes including the new design on Xenforo.
    Dismiss Notice

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,646
    Likes Received:
    86
    Trophy Points:
    0
    Occupation:
    Programmer
    Location:
    Kolkata, India
    Home Page:
    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
    thanks alot
     

Share This Page