Connecting to a MS SQLServer database in ASP

Below is the code for connecting to a MS SQLServer database using a DSN and without a DSN.

1. With a DSN

<%
Set connection = Server.CreateObject("ADODB.Connection")
connection.Open "DSN=DSNname;UID=username;PWD=password;Database=databasename"
%>

2. Without a DSN

<%
sConnString="DRIVER={SQL Server};SERVER=servername;UID=username;PWD=password;DATABASE=dbname"
Set connection = Server.CreateObject("ADODB.Connection")
connection.Open sConnString
%>

Here's an example of what the code would look like connecting to an SQLServer database without a DSN.

<%
'declare your variables
dim connection,recordset
dim SQL,sConnString
'declare SQL statement that will query the database
SQL="SELECT * FROM yourTable "
'define the connection string, specify database
'driver and the location of database
sConnString="DRIVER={SQL Server};SERVER=yourServername;UID=yourUsername;" & _ "PWD=yourPassword;DATABASE=yourDatabasename"
'create an ADO connection and recordset
Set connection = Server.CreateObject("ADODB.Connection")
Set recordset = Server.CreateObject("ADODB.Recordset")
'Open the connection to the database
connection.Open sConnString

'Open the recordset object, execute the SQL statement
recordset.Open SQL,connection
If recordset.eof then
 response.write "There were no records returned."
Else
 response.write "There are records returned."
End if

'close the connection and recordset objects freeing up resources
Recordset.Close
Set Recordset=nothing
Connection.Close
Set Connection=nothing
%>


Previous: Try and avoid SELECT *

Advertisements



MembersPro

MembersPro PayPal - ASP Membership software

Plug and play ASP membership script that integrates with PayPal to let you charge recurring membership fees.

Get your best asp web hosting provider now and save 25%