简体   繁体   中英

ASP Classic Database Connection

I want to use classic ASP to open and close a connection to a SQL Server database and let it run a procedure from the database. It has no parameters.

This is the connection details in ASP, change caps to the relevant information objDBRS(0) will be your first part of data from a select statement

Set objDBConn = Server.CreateObject("ADODB.Connection")
objDBConn.Open "Provider=sqloledb;Data Source=SQLSERVERNAME;Initial Catalog=DATABASENAME; User ID=Chris;Password=PASSWORD;"

Set objDBCommand = Server.CreateObject("ADODB.Command")

objDBCommand.ActiveConnection = objDBConn
objDBCommand.CommandText = "SQLPROCEDURENAME"
objDBCommand.CommandType = adCmdStoredProc

Set objDBRS = Server.CreateObject("ADODB.RecordSet")

objDBRS.open objDBCommand,,adOpenForwardOnly

DO WHAT YOU WANT HERE

Set objDBCommand=nothing
objDBConn.Close
Set objDBConn=nothing

Here is a tried and tested approach I use over and over again.

<%
Dim cmd, conn_string, rs, data, row, rows

'Connection String if using latest version of SQL use SQL Server Native Client
'for more examples see http://www.connectionstrings.com/sql-server/
conn_string = "Provider=SQLNCLI11;Server=myServerAddress;Database=myDataBase;Uid=myUsername;Pwd=myPassword;"

Set cmd = Server.CreateObject("ADODB.Command")
With cmd
  'No need to build ADODB.Connection the command object does it for you.
  .ActiveConnection = conn_string
  .CommandType = adCmdStoredProc
  .CommandText = "[schema].[procedurename]"
  Set rs = .Execute()

  'Populate Array with rs and close and release ADODB.Recordset from memory.
  If Not rs.EOF Then data = rs.GetRows()
  Call rs.Close()
  Set rs = Nothing
End With
'Release memory closes and releases ADODB.Connection as well.
Set cmd = Nothing

'Use Array to enumerate data without overhead of ADODB.Recordset.
If IsArray(data) Then
  rows = UBound(data, 2)
  For row = 0 To rows
    'Read data
    Call Response.Write("First Field: " & data(0, row))
  Next
Else
  'No records
  Call Response.Write("No records to display")
End If
%>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM