In this tutorial we will show you how to connect to MS SQL Server database. Everything is commented so you won't have trouble.
Connect with a DSN
DSN stands for 'Data Source Name'. It is an easy way to assign useful and easily rememberable names to data sources which may not be limited to databases alone. If you do not know how to set up a system DSN read our tutorial How to set up a system DSN.
<%
Set Connection = Server.CreateObject("ADODB.Connection") Set Recordset = Server.CreateObject("ADODB.Recordset")
Recordset.Open SQL,Connection
If Recordset.EOF Then Response.Write("No records returned.") Else
Do While NOT Recordset.Eof Response.write Recordset("FIRST_FIELD_NAME") Response.write Recordset("SECOND_FIELD_NAME") Response.write Recordset("THIRD_FIELD_NAME") Response.write "<br>" Recordset.MoveNext Loop End If
Recordset.Close Set Recordset=nothing Connection.Close Set Connection=nothing %>
Connect without a DSN (using a connection string)
Let’s look at a sample script to get an idea how to connect to MS SQL Server database without DSN:
<%
ConnString="DRIVER={SQL Server};SERVER=yourServername;UID=yourUsername;" & _ "PWD=yourPassword;DATABASE=yourDatabasename"
Set Connection = Server.CreateObject("ADODB.Connection") Set Recordset = Server.CreateObject("ADODB.Recordset")
Connection.Open ConnString
Recordset.Open SQL,Connection
Recordset.Close Set Recordset=nothing Connection.Close Set Connection=nothing %>
Note: Don't forget to replace the constants (TABLE_NAME, FIELD_NAME) with real names of tables and fields in your database.
Related Articles
MS SQL Server Connection Strings
|