ASP SQL Server Connection

 <%
 DIM objConn
 Set objConn = Server.CreateObject("ADODB.Connection")
 objConn.ConnectionString = "Data Source=123.123.12.123,1234;Database=DatabaseName;User Id=Usernm;Password=abcd1234;"
 objConn.Open

 DIM mySQL

 mySQL = "SELECT * FROM [Users] WHERE [User ID]='1'"

 DIM objRS
 Set objRS = Server.CreateObject("ADODB.Recordset")
 objRS.open(mySQL, objConn)

 Response.Write objRS("FullName")

 objRS.Close
 Set objRS = Nothing
 objConn.Close
 Set objConn = Nothing
 %>

I want to connect to a SQL Server database, read the data and close the connection. I studied examples and came up with this. But that does not work. Please guide me. Where am I mistaken?

-1
source share
2 answers
Dim rs, dbConn

Function OpenDB()
    Set dbConn = Server.CreateObject("ADODB.Connection")
    dbConn.ConnectionTimeout = 300
    dbConn.CommandTimeout = 300
    dbConn.Open "Data Source=123.123.12.123,1234;Database=DatabaseName;User Id=Usernm;Password=abcd1234;"
End Function

Function CloseDB()
    Set rs = Nothing
    if ucase(TypeName(dbConn)) = "CONNECTION" then
        dbConn.Close
        Set dbConn = Nothing
    end if
End Function

Function OpenRecordSet(recset, tablename)
    Call OpenDB()
    Set recset = Server.CreateObject("ADODB.Recordset")
    recset.Open tablename, dbConn, 0, 1
End Function

Function CloseRecordSet(recset)
    Set recset = Nothing
    Call CloseDB()
End Function

Then use

<%
Call OpenDB()
sql = "select from mytable where this = 'that'"
Set rs = dbConn.Execute(sql)
if not rs.EOF then
      ' do your stuff!
end if
Call CloseDB()
%>

http://www.shiningstar.net/articles/articles/database/datafunctions.asp?ID=AW

-1
source

Some answers suggested wrapping logic in a function that is not needed.

, , ADODB.Command. , , , ADODB.Command , Array, .GetRows() ADODB.Recordset. , ADODB.Recordset ADODB.Command Array.

Dim conn, cmd, rs, sql, data, search

'Assume value to query comes from a Request Collection.
search = Request("myvalue") & ""

conn = "Data Source=123.123.12.123,1234;Database=DatabaseName;User Id=Usernm;Password=abcd1234;"
sql = "select from mytable where this = ?"
Set cmd = Server.CreateObject("ADODB.Command")
With cmd
  'No need to handle connection let ADODB.Command create and destory it.
  .ActiveConnection = conn
  .CommandType = adCmdText
  .CommandText = sql
  .Parameters.Append(.CreateParameter("@myparam", adVarWChar, adParamInput, 50))
  .Parameters("@myparam").Value = search
  Set rs = .Execute()
  If Not rs.EOF Then data = rs.GetRows()
  Call rs.Close()
  Set rs = Nothing
End with
Set cmd = Nothing
'ADODB.Connection is closed when ADODB.Command is destroyed.

If IsArray(data) Then
  rows = UBound(data, 2)
  For row = 0 To rows
    'Return first column of the current row
    Call Response.Write("First Column of Row " & row & " is '" & data(0, row) & "'<br />"
  Next
Else
  Call Response.Write("No records")
End If
+1

Source: https://habr.com/ru/post/1651330/


All Articles