ASP Classic Database Connection - html

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
%>

Related

Arguments converted TypeError while inserting data into DB with python

Found some questions regarding this topic but none of them really solved my problem.
I'm running into some issues while trying to insert data into my SQL server, I'm pretty new in regards of Databases so my guess is that there is something wrong with how I defined the query or the values.
My code looks like this:
query = "INSERT INTO `Productos`(`IDProductos`, `ItemID`, `Nombre`, `MPN`, `Descripcion`, `URL`, `Precio`, `Departamento`, `CodigoGenerico`, `Fecha`, `Procedencia`) VALUES (?,?,?,?,?,?,?,?,?,?,?)"
for index,row in df.iterrows():
IDProductos = '???'
ItemID = row['codigoEspecificoProducto']
Nombre = row['nombreProducto']
MPN = 'null'
Descripcion = 'null'
URL = row['urlProducto']
Precio = row ['precioProducto']
Departamento = row['categoriaProducto']
CodigoGenerico = row['codigoGenericoProducto']
Fecha = 'null'
Procedencia = 'Amazon'
values = [IDProductos,ItemID,Nombre,MPN,Descripcion,URL,Precio,Departamento,CodigoGenerico,Fecha,Procedencia]
cursor.execute(query,values)
What I'm doing is basically passing data from an excel file to my database.
Is the query I'm ussing correct? It's the one I got from copying the insert that appears in the database.
I get the TypeError: not all arguments converted during string formatting when it reaches cursor.execute(query,values)
From Excel to SQL Server.
' Set a reference to: Microsoft ActiveX Data Objects 6.1 Library
Sub InsertInto()
'Declare some variables
Dim cnn As adodb.Connection
Dim cmd As adodb.Command
Dim strSQL As String
'Create a new Connection object
Set cnn = New adodb.Connection
'Set the connection string
cnn.ConnectionString = "Provider=SQLOLEDB.1;Integrated Security=SSPI;Persist Security Info=True;Initial Catalog=Northwind;Data Source=Your_Server_Name"
'Create a new Command object
Set cmd = New adodb.Command
'Open the Connection to the database
cnn.Open
'Associate the command with the connection
cmd.ActiveConnection = cnn
'Tell the Command we are giving it a bit of SQL to run, not a stored procedure
cmd.CommandType = adCmdText
'Create the SQL
strSQL = "UPDATE TBL SET JOIN_DT = '2013-01-22' WHERE EMPID = 2"
'Pass the SQL to the Command object
cmd.CommandText = strSQL
'Execute the bit of SQL to update the database
cmd.Execute
'Close the connection again
cnn.Close
'Remove the objects
Set cmd = Nothing
Set cnn = Nothing
End Sub

Access Filters not working with ADODB.Recordset connection err(Data Provider could not be initialized

We have migrated part of our Access database to mysql, this snippet simply retrieves the sql statement from a table containing form names and sql statements and then sets it as the forms recordset
The issue i have right now is although the speed is a tremendous improvement, The access front end is not completely functioning as expected right now, the Refresh and filter by text access functions do not work, simply throw error (Data Provider could not be initialized).
I believe this has something to do with us setting the recordsource to the form, is there anyway around this without a huge performance drop?
If i simply link a view from mysql into access and set the forms recordsource as that view, it takes a much longer time to load and filter
The Picture here http://puu.sh/BXw55/fe8b01d8d0.jpg Shows when the error occurs, when trying to use Access Filters
Here is the function:
Private Sub Command91_Click() 'Clear filters'
On Error GoTo ErrHandler
Dim oConn As ADODB.Connection
Dim rs As ADODB.Recordset
Dim ConnStr As String
Dim strOrderBy As String
'Creating new connection, and then using ConnectString function to connect to mysql Database'
Set oConn = New ADODB.Connection
oConn.Open ConnectString
'Clears filter fields to null'
fltrDocBaseID.Value = Null
fltrDocBaseClientDocNumber.Value = Null
fltrDisciplinesID.Value = Null
fltrDocTypeID.Value = Null
fltrDocSubTypesID.Value = Null
fltrProjectID.Value = Null
FilterOn = False
fltrDocBaseTitle1.Value = Null
fltrDocBaseTitle2.Value = Null
fltrDocBaseTitle3.Value = Null
fltrDocBaseTitle4.Value = Null
'Retrieves SQL code from refreshDS(fname As String) located in Module- SQLDatasources'
strSQL = refreshRS(Me.Name)
'Creates new recordset'
Set rs = New ADODB.Recordset
'Connects to mysql database, runs strSQL and then sets page recordset'
'to the current strSQL'
With rs
Set .ActiveConnection = oConn
.Source = strSQL
.LockType = adLockOptimistic
.CursorType = adOpenKeyset
.CursorLocation = adUseClient
.Open
End With
Set Me.Recordset = rs
'Closes recordset and connections, This is a good practice for traffic efficiency'
rs.Close
oConn.Close
Set rs = Nothing
Set oConn = Nothing

Bind Access Form/Report to results from MySQL Stored Procedure

I'm trying to change the recordset of a Report (or Form) to be the results of a dynamically called MySQL stored procedure, in the Report_Load event. Specifically, how would I set up the connection?
I've looked at Bind Access form to the results from a Stored Procedure, as well as How to bind Microsoft Access forms to ADO recordsets. I'm already successfully connecting to the stored procedure using hard-coded values in a pass-thru query, as detailed in Calling Stored Procedures and other SQL statements from MS Access 2003 (Pass Through).
Here's the example code from Bind Access form to the results from a Stored Procedure - I want to setup the connection to use MySQL instead of SQL Server:
With cn
.Provider = "Microsoft.Access.OLEDB.10.0"
.Properties("Data Provider").Value = "SQLOLEDB"
.Properties("Data Source").Value = "Server"
.Properties("Integrated Security").Value = "SSPI"
.Properties("Initial Catalog").Value = "Test"
.Open
End With
I'm using Access 2007.
Out of interest, here is the code I was using to try to modify the sp call, giving an error "32585 this feature is only available in an ADP". Gord Thompson's suggestion of modifying the actual query works, so I'm using that.
If Not CurrentProject.AllForms("foo_frm").IsLoaded Then
'use hard-coded query (stored procedure) for dev work
Exit Sub
End If
Dim action, startdate, enddate As String
action = Forms![foo_frm].txtAction
If action = "cmdDaily" Then
startdate = Forms![foo_frm].txtYesterday
enddate = Forms![foo_frm].txtToday
Else
startdate = Forms![foo_frm].cboStartDate
enddate = Forms![foo_frm].cboEndDate
End If
Dim cn As New ADODB.Connection
Dim strConnection As String
strConnection = "ODBC;DSN=Foo01;UID=root;PWD=Secret;DATABASE=bar"
With cn
.Provider = "MSDASQL"
.Properties("Data Source").Value = strConnection
.Open
End With
Dim prmStartDate, prmEndDate As New ADODB.Parameter
Dim cmd As New ADODB.Command
Set prmStartDate = cmd.CreateParameter("startdate", adDate, adParamInput)
prmStartDate.Value = CDate(startdate)
cmd.Parameters.Append (prmStartDate)
Set prmEndDate = cmd.CreateParameter("enddate", adDate, adParamInput)
prmEndDate.Value = CDate(enddate)
cmd.Parameters.Append (prmEndDate)
With cmd
.ActiveConnection = cn
.CommandText = "qux_sp"
.CommandType = adCmdStoredProc
Set Me.Recordset = .Execute
End With
You already have the report working with a pass-through query, so rather than using code to fiddle with the row source of the report why not just leave the report bound to the pass-through query and use code to tweak its SQL statement and call the stored procedure with the parameters you want?
For example, the following VBA code...
Sub TweakPassThroughQuery()
Dim testID As Long
Dim qdf As DAO.QueryDef, rst As DAO.Recordset
testID = 2 ' this is the parameter we really want to pass to the stored procedure
Set qdf = CurrentDb.QueryDefs("ptq_myproc")
Debug.Print "Existing pass-through query..."
Debug.Print " " & qdf.SQL
Set rst = qdf.OpenRecordset
Debug.Print "...returns a value like this:"
Debug.Print " " & rst!col1
rst.Close
Set rst = Nothing
' now tweak the stored procedure call
qdf.SQL = "CALL myproc(" & testID & ")"
Debug.Print "Modified pass-through query..."
Debug.Print " " & qdf.SQL
Set rst = qdf.OpenRecordset
Debug.Print "...returns a value like this:"
Debug.Print " " & rst!col1
rst.Close
Set rst = Nothing
Set qdf = Nothing
End Sub
...displays the following output:
Existing pass-through query...
CALL myproc(1)
...returns a value like this:
foo
Modified pass-through query...
CALL myproc(2)
...returns a value like this:
bar

ms access - return records from sql Stored procedure

I have an access 2010 and I want to call a sql stored proc on a sql 2008 server and return the results to a recordset or bind directly to a report.
The method below returns the error "feture not available in ADP" or something like that - It works with a Form but not with a Report.
How do I go about doing this?
Dim cn As New ADODB.Connection
Dim rs As ADODB.Recordset
Dim cm As New ADODB.Command
'Use the ADO connection that Access uses
Set cn = CurrentProject.AccessConnection
With cn
.Provider = "Microsoft.Access.OLEDB.10.0"
.Properties("Data Provider").Value = "SQLOLEDB"
.Properties("Data Source").Value = "dsidsw923"
.Properties("Integrated Security").Value = "SSPI"
.Properties("Initial Catalog").Value = "Promotions_Dev_DSI"
.Open
End With
'Create an instance of the ADO Recordset class, and
'set its properties
Set rs = New ADODB.Recordset
With cm
.ActiveConnection = cn
.CommandText = "spCheckProdWkConsist"
.CommandType = adCmdStoredProc
Set rs = .Execute()
End With
'Set the form's Recordset property to the ADO recordset
Set Me.Recordset = rs
Set rs = Nothing
Set cn = Nothing
Set cm = Nothing
Consider creating a view to wrap the results of the stored procedure (exec usp_whatever) and then create a linked table to the new view.
Also, you may be able to create a passthrough query (exec usp_whatever) that executes your stored procedure and returns your results directly. Then just bind your report or form to the query.

Return recordset from function in classic ASP

I'm at a loss on how I can return a readable recordset from a function in classic ASP.
This is what I came up with, but it's not working:
Response.Clear
Response.CharSet = "utf-8"
Response.ContentType = "text/plain"
Dim Count
Set Count = Test
Response.Write Count.Fields(0).Value
Function Test
Dim Query, Connection, Command, Recordset
Query = " blah blah blah "
Set Connection = Server.CreateObject("ADODB.Connection")
Set Command = Server.CreateObject("ADODB.Command")
Set Recordset = Server.CreateObject("ADODB.Recordset")
Connection.ConnectionString = "blah blah blah"
Connection.Open
Set Command.ActiveConnection = Connection
Command.CommandText = Query
Set Recordset = Command.Execute
Set Test = Recordset
Recordset.Close
Connection.Close
Set Recordset = Nothing
Set Command = Nothing
Set Connection = Nothing
End Function
The Response.Write Count.Fields(0).Value line yields the Item cannot be found in the collection corresponding to the requested name or ordinal. error.
Replacing it with Response.Write Count.Status I get the Operation is not allowed when the object is closed. error.
Adding Count.Open gives the The connection cannot be used to perform this operation. It is either closed or invalid in this context. error.
Edit after Mark B's answer:
I already looked at disconnected recordsets but I don't know how to use them in my example: every tutorial feeds the query directly into the recordset with Recordset.Open, but I'm using parametrized queries, and even trying many ways I couldn't obtain the same result when there's an ADODB.Command in the way.
What should I do?
Thanks in advance.
Here's the solution based on Eduardo Molteni's answer:
The function which interacts with the database:
Function Test
Dim Connection, Command, Recordset
Set Connection = Server.CreateObject("ADODB.Connection")
Set Command = Server.CreateObject("ADODB.Command")
Set Recordset = Server.CreateObject("ADODB.Recordset")
Connection.ConnectionString = "blah blah blah"
Connection.Open
Command.ActiveConnection = Connection
Command.CommandText = "blah blah blah"
Recordset.CursorLocation = adUseClient
Recordset.Open Command, , adOpenForwardOnly, adLockReadOnly
Set Recordset.ActiveConnection = Nothing
Set Test = Recordset
Connection.Close
Set Recordset = Nothing
Set Command = Nothing
Set Connection = Nothing
End Function
The code which calls the function:
Response.Clear
Response.CharSet = "utf-8"
Response.ContentType = "text/plain"
Dim Recordset
Set Recordset = Test
Response.Write Recordset.Fields(0).Value
Recordset.Close
Set Recordset = Nothing
Here's a function that returns a disconnected recordset
Function RunSQLReturnRS(sqlstmt, params())
On Error Resume next
''//Create the ADO objects
Dim rs , cmd
Set rs = server.createobject("ADODB.Recordset")
Set cmd = server.createobject("ADODB.Command")
''//Init the ADO objects & the stored proc parameters
cmd.ActiveConnection = GetConnectionString()
cmd.CommandText = sqlstmt
cmd.CommandType = adCmdText
cmd.CommandTimeout = 900
''// propietary function that put params in the cmd
collectParams cmd, params
''//Execute the query for readonly
rs.CursorLocation = adUseClient
rs.Open cmd, , adOpenForwardOnly, adLockReadOnly
If err.number > 0 then
BuildErrorMessage()
exit function
end if
''// Disconnect the recordset
Set cmd.ActiveConnection = Nothing
Set cmd = Nothing
Set rs.ActiveConnection = Nothing
''// Return the resultant recordset
Set RunSQLReturnRS = rs
End Function
Well, you are closing the recordset and connection immediately after setting the function's return variable, so that explains the error messages.
I am not a VB developer, but I think what you need to look at is Disconnected Recordsets. Take a look at this article, it's doing pretty much exactly what you want.