ASP javascript how to create an SQL SELECT statement using prepared statement - asp-classic

I am using ASP javascript to select from a MySQL database using a parameter passed by the user.
I would like to do this using a prepared statement. I have seen examples in VB script but can't figure it out in ASP JS.
I would normally do it in the following way:
var adoConnection = Server.CreateObject("ADODB.Connection");
adoConnection.Open("dsn=my-dsn;uid=userid;pwd=password;");
var getAdmin = "SELECT * FROM users WHERE username = '"+String(Request.QueryString("username"))+"'";
var rsAdmin = adoConnection.Execute(getAdmin);
I would like to change this to pass the user data in a safer way, can anyone help?

to parametrize correctly in ASP your Queries, you need to use "ADODB.Command" to execute your queries instead of using ADODB.Connection directly. ADODB.Command has method named ".CreateParameter()" that permits that you want.
Example code
'-------------------------------------------------------------------'
var oCmd = Server.CreateObject("ADODB.Command")
var sSQL = "SELECT username, action FROM userlog WHERE event_date < ? ;";
oCmd.CommandText = sSQL
oCmd.ActiveConnection= oConn
'-------------------------------------------------------------------'
var oPar = oCmd.CreateParameter("event_date",7,1,,dDate); 'Date
oCmd.Parameters.Append(oPar);
'-------------------------------------------------------------------'
.... do this until you have all the parameters appended and ....
var oRS = oCmd.Execute();
and you manipule the recordset as you wish
Aditional resources
ADODB Documentation
MSDN Example

ASP javascript is usually reffered to as JScript. If you search for '[jscript] [mysql]' on stackoverflow it will show you a question which will probably answer your question:
ADODB Command failing Execute with parameterised SQL query
You could also google 'msdn jscript ado' for additional samples.

Although calling into a database directly from browser-side code isn't a preferred method of retrieving data into the page (most folks prefer AJAX/JSON requests these days...), you could definitely improve the security of your code by converting the SQL statement to a stored procedure call.
For details, see http://andrewu.co.uk/clj/stored_procedures_with_jscript/

Related

How to trace a call to a stored procedure and get feedback out of its execution?

I have a stored procedure that I'm calling from asp.net and I'm adding 47 parameters mostly from values selected on drop downs and radio buttons and text boxes from a form. I also have (for some reason beyond my pay grade) some parameters that are set to Null..these are also a source of some hair pulling and I don't know if these are the problems or not.
Dim Parameter As SqlParameter = New SqlParameter("#type", "u")
Dim Parameter1 As SqlParameter = New SqlParameter("#user", User)
Dim Parameter2 As SqlParameter = New SqlParameter("#term", terminal)
Dim Parameter3 As SqlParameter = New SqlParameter("#url", accesslevel)
Dim Parameter4 As SqlParameter = New SqlParameter("#name", firstname & " " & lastname)
Dim Parameter5 As SqlParameter = New SqlParameter("#mgr", mgr)
Dim Parameter6 As SqlParameter = New SqlParameter("#mgrEmail", mgr)
Dim Parameter7 As SqlParameter = New SqlParameter("#phone", mgr)
Dim Parameter8 As SqlParameter = New SqlParameter("#title", titletitle)`
... and on and on until Parameter48...
Dim myCommand As New SqlCommand("dbo.proc_vsSpacAccess", conn)
myCommand.CommandType = CommandType.StoredProcedure
myCommand.Parameters.Add(Parameter)
myCommand.Parameters.Add(Parameter1)
myCommand.Parameters.Add(Parameter2)
myCommand.Parameters.Add(Parameter3)
myCommand.Parameters.Add(Parameter4)
... and on until Parameter48... and then finally I run the stored proc..
myCommand.ExecuteNonQuery()
end of subroutine...
I run this and get nothing, no feedback, nothing. How do I know what's wrong if things aren't working? do I debug from SQL Server (I can't change the stored procedure it's not mine to change btw) or try to debug the stored procedure from Visual Studio?
I REPEAT, I CANNOT CHANGE THE STORED PROCEDURE IT IS READ ONLY FOR ME..
ExecuteNonQuery won't return anything unless you explicitly catch the return value.
If you want to know how query is executing, you can view using SQL Server Profiler.
Set a break point right after ExecuteNonQuery
Let SQL Server Profiler run at the background
See the executed query
You can even copy the query from Profiler, and run it in SSMS to make sure it even works.
Let me give you some advice on debugging. First run profiler when you run your application (on dev!) and grab the SQL that is generated.
Next open up SSMS and put that SQL in it and see if it generated valid sql. Sometimes you qwill find it did not. Then the problem is in how you are building the sql. If the SQL is valid, either it ran but didn't give you a return message or the problem is the proc itself or the data in the parameters.
Then open up the stored proc to see what it does; if it is inserting to a table or updating a table, check that table in the db to see if the data was inserted or updated based on teh variables you sent. You should always have unit tests built to check the results of an action stored proc, if you do not, then write them now, so the next time you test, you know what you should see in the database as a result of running the proc.
If you did not get the action you expected, try running the proc from SSMS with the profiled data. If the data still doesn't insert or update, you may need to ask the people responsible for the proc to track down what the problem is. Likely in this case, soemthing is wrong with the particular parameters you are sending although it could bea genuiine bug of a case taht was not expected. For instance you may be sending a null for a reuired field. Not all procs are built to properly handle errors, so it may not be sending one up the chain to you.
Lets start from the point that when it comes to executing stored procedures, you need to design it to return some feedback. Just the fact that you have stored procedure, doesn't mean that you will have any feedback. For example (pseudo-code)
Create procedure MyProc()
Begin
Try
-- Do something
-- And it happens to error here
Catch
' do nothing
End Try
End
Now, this one, will never give you any info of what happened, success or failure because error is handled within
Lets look at this one now, again, pseudo-code
Create procedure MyProc(#retVal int out)
Begin
set #retVal = -1 -- assume it failed
Try
-- Do something
set #retVal = 0 -- a flag that it is success
Catch
' do nothing
End Try
End
Now, with this you can go to your vb code and test
myCommand.ExecuteNonQuery()
Dim val as Object = myCommand.Parameters(0).Value
If CInt(val) = 0 Then
' success route
Else
' error route
End If
Basically, this is the example of one of the few methods how to obtain info about state of execution of your stored procedure. But again, you need to code for this.
Now, if you want to know in details, what is your SP doing while it is executing, again, you need to code for this. You can create a log table, in which you will store data that you scrape within your SP. I've seen designs where each SP had one parameter #debug. And, when called in debug mode, it would post logs about its execution data.

How to pass custom sql command to fastreport.net through application using c#?

I start using fastreport.net to generate report in c# since Crystal reports is not compatible with .net4. Its so simple but it is so complicated also.
I try to pass an sql command to my report through my applicate but it doesnt work.Can anyone help me with that ? Here is the Code :
Report rpt = new Report();
rpt.Load("H:\\MyReport.frx");
rpt.SetParameterValue("Parameter", "Provider=SQLOLEDB.1;Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=Confictionary");
FastReport.Data.TableDataSource data = rpt.GetDataSource("Contact") as FastReport.Data.TableDataSource;
data.SelectCommand = "SELECT * from contact";
rpt.Prepare();
rpt.ShowPrepared();
It throws an exception in line 5 : "Object reference not set to an instance of an object."
Please sb help me.
tnx a lot
I think SQL command should be in report template set, not dynamically, unless this would be used only for the first time for creating report file.
i use this:
FReport.SetParameterValue("SQL_rysys", ConnectionString);
if (FReport.Dictionary.Connections.Count > 0)
{
FReport.Dictionary.Connections[0].ConnectionString = ConnectionString;
FReport.Dictionary.Connections[0].ConnectionStringExpression = "[SQL_rysys]";
FReport.Dictionary.Connections[0].CommandTimeout = 60;
}
This code assigns value for Parameter "SQL_rysys" (SQL_connection in english), i pass SQL connection string. Also if there is any connections in datasource dictionary-i assign connection string to the first one.
So my reports always gets the correct connection string, BUT the SQL query is already included IN REPORT. Cause there is no other way of creating report in designer without using query to get data, and that query is saved in XML report file (frx).
I was asking in fastreport support how to assign query, but their support is AWFUL and noobs works there.

Output params and Stored Procedure

I've googled but none of the solutions seems to work for me!
I have a SPROC in SQL Server which has an input param and also an output parameter being set within the SPROC.
using classic ASP, I want to retrieve the value of that output parameter but nothing seems to get set (but I can see the output parameter working correctly when executing in the SQL Server Management Studio)
OpenConnection
Set cmdTemp = Server.CreateObject("ADODB.Command")
cmdTemp.CommandType = 4 'adCmdStoredProc
Set cmdTemp.ActiveConnection = dbConn
cmdTemp.CommandText = "GetCerts"
cmdTemp.Parameters.Refresh
cmdTemp.Parameters(1) = "ABC123"
cmdTemp.Parameters(2).Direction = 2 'Output
Set reader = cmdTemp.Execute
Response.Write(cmdTemp.Parameters(2)) ' Nothing is displayed at all.
CloseConnection
I tried using the named parameters approach but always got an error saying that the parameters are out of range, wrong arguments or wrong type (Something similar to this).
Really... getting a headache. I just want the OUTPUT param value set from the SPROC (2nd parameter in the SPROC)
Check for errors:
Set reader = cmdTemp.Execute
If Err.number <> 0 or dbConn.Errors.Count <> 0 Then
'Do something to handle the error
End If
Do you have permissions to execute the stored procedure? i.e. the credentials of the ASP user...
Execute Stored Procedure from Classic ASP
It seems after a long long investigation that what I am trying to do is not possible (but it is in .NET). Seems I need to execute the command twice, first time getting the output parameters values then the next time to display the results. Awful. Praise .NET!
Most collections in the COM world use zero-based indexing. Try using Parameters(0) as the input parameter and Parameters(1) as the output parameter.

ADODB.Recordset error '800a0bb9' : Arguments are of the wrong type

Set rsPlanID = Server.CreateObject("ADODB.Recordset")
rsPlanID.CursorLocation = adUseClient
strSQL = "SELECT PlanID FROM ATTJournals WHERE ATTUserDataID = " & ATTUserDataID
rsPlanID.Open strSQL, m_objConn, adOpenStatic, adLockOptimistic
If Not rsPlanID.EOF Then
response.Write "New PlanID:" & rsPlanID("PlanID")
End If
The above code is in classic asp.
I am getting the following error:
ADODB.Recordset error '800a0bb9'
Arguments are of the wrong type, are out of acceptable range, or are in conflict with one another.
Dows anyone know the cause this error and how to fix it?
The most like cause is that you haven't included "ADOVBS.INC" or the equavalent META:-
<!--METADATA
TYPE="TypeLib"
NAME="Microsoft ActiveX Data Objects 2.6 Library"
UUID="{00000206-0000-0010-8000-00AA006D2EA4}"
VERSION="2.6"
-->
Hence the adxxxx constants do not exist. However your primary mistake is not including Option Explicit at the top your script. This will save you bucket loads of time hunting silly mistakes and typos.
BTW What happens if ATTUserDataID contained "0; DELETE ATTJournals;" ?
Avoid composing SQL using concatenation like the plague. Search for "ASP SQL Injection" to find examples of using parameterised command objects instead.
Unless you need to navigate back and forth in the recordset, just use the default settings:
strSQL = "SELECT PlanID FROM ATTJournals WHERE ATTUserDataID = " & ATTUserDataID
Set rsPlanID = m_objConn.Execute(strSQL)
Also, your code is wide open for SQL Injection attacks - you better learn about it and change your code to use Parameters instead.
I feel like I searched the whole internet and couldn't find the solution to this problem, and just as I was about to give up, I realized that I had declared my connection variable within an "If" statement and because the if statement did not execute neither did my command to the database giving the error as mentioned in your question.
First, when I devoleped application with vbscript I used always the numbers to open a recordset. I recommend following line:
rsPlanID.Open strSQL, m_objConn, 3, 3
Make sure that you include the file adovbs.inc first. The numbers are conntected to the different types of recordset properties. And don't foregt to open the databse connection first.
Second, I think you don't need the line
rsPlanID.CursorLocation = adUseClient
Thrird, see also this thread. Maybe it is a good template for you.
Function SQL_getRecordset(strQuery)
'On Error Resume Next
'Create Database connection object
Set objConnection = CreateObject("ADODB.Connection")
'Create Recordset object
Set objrecordset = CreateObject("ADODB.Recordset")
'Specify the connection string
strConnectionstring = "Provider=SQLOLEDB.1;Data Source=*<Server name>*;Initial Catalog=*<database>*;Integrated Security=SSPI"
objConnection.Open strConnectionstring
'Execute the Query
Set objrecordset = objConnection.Execute(strQuery)
'Return Recordset
Set SQL_getRecordset = objrecordset
'Release objects from the memory
Set objConnection = Nothing
Set objrecordset = Nothing
End Function

Why is my asp.net causing a runtime error?

I am trying to connect to a database on my local server. The database is called "dbtest." Of course, I have left off my actual password and replaced it with "password."
This is the typical code I see on every tutorial, but it doesn't work at all. Please help.
<%
Dim con, rs
con = Server.CreateObject("ADODB.Connection") 'I think it is something to do with this line
con.Open "Provider=sqloledb;SERVER=localhost;DATABASE=dbtest;UID=administrator; PWD=password;"
rs = Server.CreateObject("ADODB.Recordset")
%>
This is not asp.net. This is classic ASP
You have to read about creating a database driven webapp first.
Read about SqlDataSource and GridView controls. You won't need any code.
here: http://www.asp.net/data-access/tutorials/querying-data-with-the-sqldatasource-control-cs
The tutorials you are following may be a little out of date, .net includes updated classes for SQL data access, have a look here
http://msdn.microsoft.com/en-us/library/system.data.sqlclient.aspx
Particularly at the SqlConnection class and SqlCommand class.
There is a useful tutorial that can be found here.
The equivalent of the ADODB.Recordset would be the SqlDataReader class.

Resources