How to browse a query result? - vbscript

I have a query:
sqlPU = "SELECT num_uti FROM myTable WHERE C_IDENT_A = '5'
but I didn't know to browse my result.
I try this but it doesn't work
req.Open sqlPU, oConn
If Not req.EOF Then
Set resultSet = oConn.Execute(sqlPU)
For Each result In resultSet
WScript.Echo resultSet.Fields(num_uti).Value
Next
End if

Try restructuring the code like this;
Dim oConn, req, sqlPU
'Create connection
Set oConn = CreateObject("ADODB.Connection")
Call oConn.Open("yourconnectionstring")
'Set query
sqlPU = "SELECT num_uti FROM myTable WHERE C_IDENT_A = '5'"
'Open recordset
Set req = CreateObject("ADODB.Recordset")
Call req.Open(sqlPU, oConn)
'Loop the return data
Do While Not req.EOF
'Output field called num_uti.
WScript.Echo req.Fields("num_uti").Value
'Move to next record
Call req.MoveNext()
Loop
'Clean-up
Call req.Close()
Set req = Nothing
Call oConn.Close()
Set oConn = Nothing
The code in the question has a few issues,
The sqlPU query string is missing a string termination character (") and will cause a syntax error.
When you call .Open() on a ADODB.Recordset it is populated and can be traversed using a Do loop and .MoveNext() method, the extra .Execute() you do is not required and re-runs the same query again. The .MoveNext() method tells the ADODB.Recordset to move it's pointer 1 record, once it reaches the end the value of .EOF will equal True. Without .MoveNext() the pointer will not move past the end of the file (EOF) and the loop will run indefinitely or until the script falls over, neither of which is good.
Referencing columns using .Fields() collection requires either an index (ordinal numeric value starting from 0) or a string containing the alias of the column (in this case "num_uti"). In the original code the column alias wasn't a string which means VBScript would assume it's a variable called num_uti and because num_uti is uninitialised it would fail.

Related

Recordset not getting updated

I have created a form to allow a user to change their password.
I created a recordset and used edit/update to save it in a query, but the new password is not being saved in the query.
My code is as follows:
Private Sub txtNewPass2_AfterUpdate()
Dim db As DAO.Database
Dim rst As DAO.Recordset
Set db = CurrentDb
Set rst = db.OpenRecordset("qryUsers", dbOpenDynaset)
If Me.txtNewPass1 = Me.txtNewPass2 Then
rst.MoveFirst
Do Until rst.EOF
If rst!NName = CboUserName.Column(0) Then
rst.Edit
rst!Password = txtNewPass2.Value
rst.Update
End If
rst.MoveNext
Loop
DoCmd.Openform("frmLogin")
Else: MsgBox "Passwords not Matching"
End If
End Sub
The expression:
DoCmd.Openform("frmLogin")
Will result in a syntax error, as the parentheses surrounding the arguments are not required when the value returned by the function is not used.
However, you may find it cleaner to simply execute a SQL statement to perform the update, rather than iterating over the recordset, i.e.:
Private Sub txtNewPass2_AfterUpdate()
If txtNewPass1 = txtNewPass2 Then
With CurrentDb.CreateQueryDef("", "UPDATE qryUsers SET qryUsers.Password = ?pwd WHERE qryUsers.NName = ?usr")
.Parameters(0) = txtNewPass2
.Parameters(1) = CboUserName.Column(0)
.Execute
End With
DoCmd.Openform "frmLogin"
Else
MsgBox "Passwords not Matching"
End If
End Sub
Using parameters of course to account for users better known as Bobby Tables.

Cannot change the ActiveConnection property of a Recordset object

I'm trying to open a recordset such that I can get an accurate value for RecordCount. I have some code that successfully does this by using Recordset.Open with the adOpenStatic and adLockReadOnly constants. However, when I use the following code.
With cmd
.ActiveConnection = db
.CommandType = adCmdStoredProc
.CommandText = "doGetBookingCrewDetails"
.Parameters.Append .CreateParameter("#bookingid", adInteger, adParamInput)
.Parameters("#bookingid") = 42943
.Parameters.Append .CreateParameter("#starttime", adDBTimeStamp, adParamInput)
.Parameters("#starttime") = "07/10/2016 00:00"
End With
Set rsCr = Server.CreateObject("ADODB.Recordset")
rsCr.Open cmd, db, adOpenStatic, adLockReadOnly
I get the error
0x800a0e7b - ADODB.Recordset: Cannot change the ActiveConnection property of a Recordset object which has a Command object as its source.
The above code returns the correct set of results when using Command.Execute, but then I can't specify the constants that seem to make the row count property work.
How do I make this work?
Here are some points from Open Method (ADO Recordset):
The ActiveConnection property is read-only for Recordset objects whose Source property is set to a valid Command object, even if the Recordset object is not open.
and
the activeconnection parameter is optional.
also
If you pass a Command object in the Source argument and also pass an ActiveConnection argument, an error occurs. The ActiveConnection property of the Command object must already be set to a valid Connection object or connection string
So in short, try not passing db into rsCr.open at all.
Something like this:
rsCr.Open cmd, , adOpenStatic, adLockReadOnly

Classic ASP Iterate through and Object

I'm a PHP developer, learning ASP.
I've become very reliant on PHP's useful functions: print_r() and var_dump() to see what an array or object contains.
I don't always know what columns are in a Db Table. So, when a SELECT * From Tbl is queried, and the objRS is populated, would I be able to view what the entire object's contents are?
Is this possible in ASP?
<% `my simple Select statement
Dim strDbConnection
Dim objConn
Dim objRS
Dim strSQL
strDbConnection = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=d:\test.mdb;"
Set objConn = Server.CreateObject("ADODB.Connection")
objConn.Open(strDbConnection)
strSQL = "SELECT * FROM persons"
Set objRS = objConn.Execute(strSQL)
If objRS.EOF Then
Response.Write("No items found")
Else
Do While Not objRS.EOF
' show all columns I can extract here....
objRS.MoveNext()
Loop
End If
objRS.Close()
Set objRS = Nothing
objConn.Close()
Set objConn = Nothing
%>
-- I would like to see what's coming back at me in the objRS, and then cherry-pick the columns after I know what I have access to.
Is there something similar to what I'm used to?
ie: print_r()
You can use objRS.fileds(j).name and objRS.fields(j).value to get the name of columns and values.
For example:
[...]
for j = 0 to objRS.fields.count - 1
response.write(objRS.fields(j).name & " = " & objRS.fields(j).value)
next

VB6 module to pass recordset to form

lets call it modUser.
In this modUser I have a ADODB record set
Now from this modUser, I would like to open a form. Lets call it frmUser2.
when this frmUser2 initialize. I would like to use the recordset that I already have from modUser. How do I pass this recordset from modUser to frmUser2?
I tried creating a public sub under frmUser2. But I get an error that says "Run time error 13 type mismatch"
here is a snippet
sSQL = "select name from employee"
rs.Open sSQL, ADOCon, adOpenKeyset
If rs.RecordCount > 1 Then
frmUser2.PopulateList(rs)
End if
in frmUser2 I have the public function ( i tried sub too)
Public Function PopulateList(rs As ADODB.Recordset)
For Count = 0 To rs.RecordCount - 1
LstModels.AddItem rs(0)
rs.MoveNext
Next
rs.close
End Function
I tried show , and I can get the form to appear, but I have no way to pass the record set.
frmUser2.Show
Please help. Thank you
I'm not a fan of how you're trying to do this, but working with what you want to do, first create a public Recordset property in your form and assign the recordset to it from your module before showing the form.
Module code:
Dim objForm As frmUser2
sSQL = "select name from employee"
rs.Open sSQL, ADOCon, adOpenKeyset
If rs.RecordCount.EOF = False Then
Set objForm = New frmUser2
frmUser2.Recordset = rs
frmUser2.Show
End if
Form Code:
Private Sub Form_Load()
If Not Recordset Is Nothing Then
PopulateList
End If
End Sub
Public Function PopulateList()
Recordset.MoveFirst 'defensive, make sure we're on the first record
LstModels.Clear
Do While Recordset.EOF = False
LstModels.AddItem Recordset(0)
Recordset.MoveNext
Next
Recordset.Close
End Function
I think it would be preferable for the module to have a public method that returns an employee recordset. Your form would call that method when it needs the data. Set rsEmployees = modUser.GetEmployees()

Can't access multiple records being returned by sql via ADODB.Recordset object

When I execut the sql direct it returns 4 records. when I execute the oraCommand.Execute the oraResults object shows only 1 record returned it should have a count of 4.
Hence I can get the value and name for the single record. Question is how do I get the other 3 records? I have tried set oraResults=oraResults.NextRecordSet() and I get error saying not supported!
Any help will appreciated.
This is the snippet of the code:
set oraCommand = CreateObject("ADODB.Command")
'set connection and sql statement
set oraCommand.ActiveConnection = oraConnection
oraCommand.CommandText =oraSQLStatement
oraCommand.CommandType = 1 ' commandText
oraCommand.Prepared = True
set oraResults = CreateObject("ADODB.Recordset")
'run the sql
set oraResults = oraCommand.Execute
oraResults.Fields(0).Name - Name from first record is returned
oraResults.Fields(0)>Value - Value from first record is returned
Try something like this: loop through the oraResults recordset and read the records:
Do until oraResults.EOF
Response.Write oraResults("firstFieldName")
Response.Write oraResults("secondFieldName")
oraResults.MoveNext
Loop
Here's a link that might help.

Resources