Connecting to MSSQL in ASP.NET with a DSN
This script demonstrates connecting to a MSSQL database in ASP.NET with a DSN. The script will make the connection and then output all the rows of a specified table.
// Set your connection string.
// Replace id, pwd, database_name and mssqlX.easycgi.com with appropriate values
Dim connString as string = "user id=id; password=pwd; initial catalog=database_name; data source=mssqlX.easycgi.com"
Dim myConnection as New SqlConnection(connString)
// Create the command object, passing in the SQL string
Const strSQL as String = "SELECT * FROM Employees"
Dim myCommand as New SqlCommand(strSQL, myConnection)
// Open connection to the database
myConnection.Open()
// Set the datagrid's datasource to the results of the query
dgPopularFAQs.DataSource = myCommand.ExecuteReader(CommandBehavior.CloseConnection)
// Bind data to Datagrid
dgPopularFAQs.DataBind()
// To display results
<asp:datagrid id="dgPopularFAQs" runat="server" />
<!------------------- The entire script is shown below ----------------------------------->
FileName: test.aspx
<% @Import Namespace="System.Data" %>
<% @Import Namespace="System.Data.SqlClient" %>
<script language="vb" runat="server">
Sub Page_Load(sender as Object, e as EventArgs)
BindData()
End Sub
Sub BindData()
'1. Create a connection
Dim connString as string = "user id=id; password=pwd; initial catalog=database_name; data source=mssqlX.easycgi.com"
Dim myConnection as New SqlConnection(connString)
'2. Create the command object, passing in the SQL string
Const strSQL as String = "SELECT * FROM Employees"
Dim myCommand as New SqlCommand(strSQL, myConnection)
'Set the datagrid's datasource to the datareader and databind
myConnection.Open()
dgPopularFAQs.DataSource = myCommand.ExecuteReader(CommandBehavior.CloseConnection)
dgPopularFAQs.DataBind()
End Sub
</script>
<asp:datagrid id="dgPopularFAQs" runat="server" />
1/5/2008 2:16:14 AM
Category
Database Connection Strings
Back