I am using visual basic as the coding language.
conSQL.Open()
Dim cmd As New SqlCommand("update Phd_Student set student_name = '" + studentnameTextBox.Text + "' where student_id = '" + studentidno.Text + "'", conSQL)
cmd.ExecuteNonQuery()
conSQL.Close()
This does not change the value of the record. I created a breakpoint at line 2 and found that the value of studentnameTextBox.Text in the query is the old value even though I changed the text of the textbox in the form.
Would appreciate any help.
This code isn't anywhere close to being secure. Validate any input information before you use it in a query and consider using stored procedures as well.
And we'll need more information about the page state when you're trying to do this.
Also, put this code in an exception block and in the Finally block put the SQL close command. If anything blows up you're going to want to make sure that the connection is still closed and Finally takes care of that.
Related
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.
I'm a web applications developer, using Classic ASP as server side script.
I always protect my apps from SQL injection by using a simple function to double single apostrophe for string parameters.
Function ForSQL(strString)
ForSQL = Replace(strString, "'", "''")
End Function
For numeric parameters, I use the CInt, CLng and CDbl functions.
I often write concatenated query; I don't always use stored procedure and I don't always validate user inputs.
I'd like to ask you if someone can show me a working attack against this line of code:
strSQL = "SELECT Id FROM tUsers WHERE Username='" & _
ForSQL(Left(Request.Form("Username"),20)) & "' AND Password='" & _
ForSQL(Left(Request.Form("Username"),20)) & "'"
It could be a banality but I've never found a kind of attack that works.
I've always found "sqli helper 2.7" (you can download it) to find most/all SQL injections. I'm not sure if this will help at all, but it will at least help test for all of the SQL comments and everything. I remember on one of my sites it found a main SQL injection to dumb all of my database data. It's not exactly what you're looking for, but it might be able to find a way through.
There is no functioning SQL injection for input sanitized this way. The downside is retrieving data from the database is you have to replace on double apostrophes.
sDataRetrievedFromDatabase = Replace(sDataRetrievedFromDatabase, "''", "'")
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
Im kinda going a little crazy here. I moved my web application to a server and im getting this error below, but on my localhost it works great. Im kinda at a loss of what i should try. Any help would be very much appreciated. Im finding that the error has to have something to do with the dataset not pulling back any data, when I do a for each statement. But the weird thing is that I do a for each statement on another page and it works fine. Here is my for each statement, that im assuming doesnt work. The reason im assuming it b/c when i test it on local it works fine:
Dim retObj As New ClassLibrary1.sql_class
For Each row As DataRow In retObj.sel_all_email_list(company).tables(0).rows
email += row("EMAIL_ADDRESS") & "/"
Next
'*****************************
sql_class
query = "SELECT * " _
& " FROM EMAIL_LIST " _
& " WHERE UCASE(COMPANY) = '" & company & "'"
Dim adapter As New OleDbDataAdapter(query, myConnection)
Dim ds As New DataSet
Try
myConnection.Open()
adapter2.Fill(ds, "test_table")
*returns the dataset, didnt want to type all of the code
Catch ex As Exception
Finally
myConnection.Close()
End Try
'*****************************************************
Error:
Exception Details: System.IndexOutOfRangeException: Cannot find table 0.
Check the SQL DB running in Production.
The SQL statement used to fill the Dataset isn't returning any data. That leads to the Dataset not having any tables.
As a result when you make your call to Dataset.Tables(0) a System.IndexOutOfRangeException gets thrown (as there are no tables in the Tables collection).
You can mitigate against this by calling Dataset.Tables.Count to ensure it has items before attempting to access the collection.
If retObj.sel_all_email_list(company).tables.count > 0 Then
'Do something
End If
' Setting variables
Dim con, sql_insert, data_source
data_source = "project_db"
sql_insert = "insert into cart ( UserID,Count,ProductName,ProductDescription,ProductPrice) values ('"&user_id&"','"&count&"','"&product_name&"','"&product_description&"','"&product_price&"')"
' Creating the Connection Object and opening the database
Set con = Server.CreateObject("ADODB.Connection")
con.Open data_source
' Executing the sql insertion code
con.Execute sql_insert
' Done. Now Close the connection
con.Close
Set con = Nothing
AS you can see , it is a simple code . and it worked in my local host for 5 or 6 times. but now it didn't work. What's the problem ? I think , it's about my database or memory. i setup 2 different iis in 2 different computer and they behave same... please help..
Thanks
Does it give you any error message? Make sure all the values you are inserting actually have values and are not blank or null. You can check this by response.write all the values and then response.end to see if they contain any values.
I bet it's a data-dependent error. You should be using ADO parameters. Those will ensure that extraneous SQL-unfriendly characters in your input do not adversely affect your database operation. You should also use them to guard against SQL injection issues.
Some docs are available at http://msdn.microsoft.com/en-us/library/ms675869(VS.85).aspx, and you can google for "ADO parameters" and find many relevant examples.
I believe that 'data_source' should be focused on (and agreed with Tom Gullen as regards to error messages. Always use Option Explicit at the top of your pages).
con.Open either expects some DSN parameters or a database connection string to be passed within 'data_source'.
Examples, respectively :
data_source = DSN_Database, DSN_User, DSN_Password
(these 'DSN_' parameters are found/set in your DSN configuration)
OR :
data_source = "Driver={SQL Server};Server=server.domain.com;Database=project_db;uid=MyUser;pwd=MyPass;""