I am an ASP beginner trying to make a very simple page. The functionality is to accept two inputs from the user and display a report based on those on the next page. The data for the report is fetched a SQL query on the ASP page.
This is what I have done till now:
Set objConn = Server.CreateObject("ADODB.Connection")
objConn.Open "Provider=MSDAORA;
Data Source=şemam;
User Id=xyz;
Password=xyz;"
aranan = Request("aranan")
Set objRs = objConn.Execute("select * from my_department where user_id = <input from user>")
if objRs.BOF and objRs.eof then
response.end
end if
The problem I am facing is that I cannot find how to properly pass the user input in the query.
Please help!
Use ? as a placeholder, then pass the parameters into the Execute method.
dim paramArray(0)
paramArray(0) = 123
Set objRs = objConn.Execute("select * from my_department where user_id = ?", paramArray)
To send parameters to a database query you need to use a command-object.
Set objConn = Server.CreateObject("ADODB.Connection")
objConn.Open "Provider=MSDAORA;" & _
"Data Source=şemam;" & _
"User Id=xyz;" & _
"Password=xyz;"
aranan = Request("aranan")
Set objCmd = Server.CreateObject("ADODB.Command")
Set objCmd.ActiveConnection = objConn
objCmd.CommandText = "SELECT * FROM my_department WHERE user_id = ?"
objCmd.CommandType = 1
Set objRs = objCmd.Execute(, array(aranan))
if not objRs.EOF then
' Do whatever you need to with the result...
end if
objRs.Close
objConn.Close
Don't end the response before you closed the connection otherwise you will end up exhausting your connectionpool.
Related
I have a really weird issue with a VBA function running in Access. When this function is called, something happens to Access that keeps it from truly quitting in the Task Manager. If this function does not run, Access will quit normally. I feel like it has something to do with passing a form object as a parameter, but I can't understand why this is happening.
The Call to the function looks like this:
...
With Forms!frmbuytool
'...setting visible properties of form objects
SetColumnOrder (!sfmReordersView.Form)
End with
...
The function looks like this:
Public Sub SetColumnOrder(frm As Form)
Dim db As Database
Dim rs As Recordset
Dim Username As String
Dim DataSheetID As Integer
Set db = CurrentDb
Username = Environ("USERNAME")
Set rs = db.OpenRecordset("SELECT DatasheetID FROM sysDataSheets WHERE DataSheetName = """ & frm.Name & """")
DataSheetID = rs!DataSheetID
'load up user settings
Set rs = db.OpenRecordset("SELECT * FROM sysUserSettings WHERE Username = """ & Username & """ AND DatasheetID = " & DataSheetID)
'if no settings are found for the user, use the defaults
If rs.EOF Then
If IsRowUser Then
Set rs = db.OpenRecordset("SELECT * FROM sysUserSettings WHERE Username = ""ROW_Default"" AND DatasheetID = " & DataSheetID)
Else
Set rs = db.OpenRecordset("SELECT * FROM sysUserSettings WHERE Username = ""CAN_Default"" AND DatasheetID = " & DataSheetID)
End If
End If
'Apply settings
Do While Not rs.EOF
With frm.Controls(rs!ColumnName)
.ColumnOrder = rs!ColumnOrder
.ColumnWidth = rs!ColumnWidth
.ColumnHidden = rs!ColumnHidden
End With
rs.MoveNext
Loop
frm.Refresh
Set frm = Nothing
Set rs = Nothing
Set db = Nothing
End Sub
I added the "Set frm = Nothing" thinking that somehow the form object is not being released, but it didn't help.
Thanks for any insights you can provide!
The call with extra parentheses
SetColumnOrder (!sfmReordersView.Form)
was the problem. You are evaluating the form object instead of just passing it as reference. Use
Call SetColumnOrder(!sfmReordersView.Form)
or
SetColumnOrder !sfmReordersView.Form
I am trying to read JPG images from MS-Access database using the following code in classic ASP:
Response.Expires = 0
Response.Buffer = TRUE
Response.Clear
Response.ContentType = "image/jpg"
Set cn = Server.CreateObject("ADODB.Connection")
cn.Open "Provider=Microsoft.Jet.OLEDB.4.0; Data Source=" & Server.MapPath("/database/database.mdb")
sqlString = "Select * from tblBusinessImages where fldID = " & request.querystring("id")
Set rs = cn.Execute(sqlString)
Response.BinaryWrite rs("fldImageData")
Response.End
But I keep getting an error telling that the browser can't read or display the image.
The database field 'tblBusinessImages' is an OLE field, and the image is saved into it by copy-paste, only for testing purpose at this time (could this be a wrong way?)
Now I know that MS-Access saves extra data in the BLOB object (as MSDN says here:
If any extraneous information is contained in the BLOB data, this will
be passed by this script, and the image will not display properly.
This becomes important when you realize that most methods of placing
images into BLOB fields place extra information in the form of headers
with the image. Examples of this are Microsoft Access and Microsoft
Visual FoxPro. Both of these applications save OLE headers in the BLOB
field along with the actual binary data.
)
My question is how do I read the RAW image data from a BLOB without the extra data/headers that MS-Access saves?
Thanks.
After a day of work I realized what the problem was: The problem was in the way the picture was saved to the database (manually).
In order to save images to database, the following code should be used:
Dim fileName
Dim conn
Dim rsTemp
Dim fldID
Dim sSQL
Dim mystream
Set mystream = Server.CreateObject("ADODB.Stream")
mystream.Type = 1
mystream.Open
mystream.LoadFromFile "D:\Desktop\My Downloads\compose1.jpg"
Set conn = Server.CreateObject("ADODB.Connection")
Set rsTemp = Server.CreateObject("ADODB.Recordset")
conn.Open "DRIVER=Microsoft Access Driver (*.mdb);DBQ=" & Server.MapPath("/database/database.mdb")
sSQL = "Select fldImageData from tblBusinessImages where fldID = 1;"
rsTemp.Open sSQL, conn, 3, 3
rsTemp.Fields("fldImageData").AppendChunk mystream.Read
rsTemp.Update
rsTemp.Close
set mystream = nothing
And in order to read an image from MS-Access database, this code should be used:
Dim conn
Dim rsTemp
Dim sSQL
Dim fldID
fldID = Request.QueryString("id")
If Not fldID = "" And IsNumeric(fldID) Then
Set conn = Server.CreateObject("ADODB.Connection")
Set rsTemp = Server.CreateObject("ADODB.Recordset")
conn.Open "DRIVER=Microsoft Access Driver (*.mdb);DBQ=" & Server.MapPath("/database/database.mdb")
sSQL = "Select * from tblBusinessImages where fldID = " & request.querystring("id")
rsTemp.Open sSQL, conn, 3, 3
If Not rsTemp.EOF Then
Response.ContentType = "image/jpeg"
Response.BinaryWrite rsTemp("fldImageData")
Else
Response.Write("File could not be found")
End If
rsTemp.Close
conn.Close
Set rsTemp = Nothing
Set conn = Nothing
Else
Response.Write("File could not be found")
End If
This way the image data will be saved as Long Binary Data in the OLE field in the database. When read, it will be posted to the browser as a readable image data.
I want to use combobox selected value as query to pull another data from mysql database. Let's say Combobox selected value as id. then I will use this id to pull another details related to this id such as supplier, cost etc. to display in label option. I used following code but it doesn't work.
sqlQa = "select Description from matcat_select where BOF like 'MAIN';"
rs.Open sqlQa, oConn, adOpenStatic
With rs
'Set .ActiveConnection = Nothing 'Disconnect the recordset.
k = .Fields.Count
'Populate the array with the whole recordset.
vaData = .GetRows
End With
'Manipulate the Combobox's properties and show the form.
With UserForm1
With .ComboBox1
.Clear
.BoundColumn = k
.List = Application.Transpose(vaData)
.ListIndex = -1
End With
End With
'Manipulate the Combobox's properties and show the form
Set rs1 = CreateObject("ADODB.Recordset")
sqlQb = "Select EOF From matcat_select Where Description = '" & ComboBox1.Value & "';"
rs1.Open sqlQb, oConn
While Not rs1.EOF
Label6.Caption = rs1("EOF")
rs1.MoveNext
Wend
Please check my code and correct me if I am wrong. Also, each time I made query in mysql via vba am I need to establish a connection?
If Not rs1.EOF Then
Label6.Caption = rs1("EOF")
Else
Label6.Caption = ""
End If
Try this
While Not rs1.EOF
Label6.Caption = rs1("EOF")
rs1.MoveNext
Wend
For the select statement
sqlQb = "Select EOF From MyTable Where Description = '" & ComboBox1.Value & "';"
ComboBox is not a text box. To get the selected value, use .Value method.
Yes you need a connection when you want to execute any queries, your VBA is not a database itself, it doesn't knows what you want.
recordset.Open Source, ActiveConnection, CursorType, LockType, Options
http://msdn.microsoft.com/en-us/library/windows/desktop/ms675544(v=vs.85).aspx
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
%>
In an absolute emergency, I am trying to go through my website and add parameterized queries. I'm a newbie and have only just learnt about them.
My problem is, I only know a very little about connection types and all of the examples I'm seeing are using another methods of connection, which is confusing me. I don't particularly want to change the way I connect to my DB, as it's on lots of pages, I just want to update my queries to be safer.
This is how I have been connecting to my DB:
Set connContent = Server.CreateObject("ADODB.Connection")
connContent.ConnectionString = "...blah...blah...blah..."
connContent.Open
and this is the SQL bit with parameters:
username = Trim(Request("username"))
connContent.Prepared = True
Const ad_nVarChar = 202
Const ad_ParamInput = 1
SQL = " SELECT * FROM users WHERE (username=?) ; "
Set newParameter = connContent.CreateParameter("#username", ad_nVarChar, adParamInput, 20, username)
connContent.Parameters.Append newParameter
Set rs = connContent.Execute(SQL)
If NOT rs.EOF Then
' Do something...
End If
rs.Close
It's obviously not working but I need to know if I can actually achieve this using the connection I have or am I missing something altogether that's stopping it from working?
Before I go forth and spend the next 2 days debugging something I'm unfamiliar with, I would like to know I'm at least on the right track...
The code in your second snippet is correct, but should be applied to a new ADODB.Command object, not to the Connection object:
username = Trim(Request("username"))
'-----Added this-----
Dim cmdContent
Set cmdContent = Server.CreateObject("ADODB.Command")
' Use this line to associate the Command with your previously opened connection
Set cmdContent.ActiveConnection = connContent
'--------------------
cmdContent.Prepared = True
Const ad_nVarChar = 202
Const ad_ParamInput = 1
SQL = " SELECT * FROM users WHERE (username=?) ; "
Set newParameter = cmdContent.CreateParameter("#username", ad_nVarChar, ad_ParamInput, 20, username)
cmdContent.Parameters.Append newParameter
cmdContent.CommandText = SQL
Set rs = cmdContent.Execute
If NOT rs.EOF Then
' Do something...
End If
rs.Close
By the way, there was a typo with the spelling of adParamInput instead of ad_ParamInput (corrected in my example).