Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
SqlQuery = "INSERT INTO GradeTable(Grade,UserID,RegDate)Values('" & TxtGrade.Text.Trim & "','" & UserID & "','" & DTBReg.Value & "'Where GradeTable.StudentID ='" & StudentID & "' and GradeTable.CourseID= '" & CourseID & "') "
It seems for what you are trying to do, that what you need is an UPDATE statement and not an INSERT as you are writing. This seems a much more appropiate query:
UPDATE GradeTable
SET Grade = #grade,
UserID = #UserID,
RegDate = #RegDate
WHERE StudentID = #StudentID AND CourseID = #CourseID
Note that I used parameters and not the value of your textbox. This is because you are being vulnerable to one of the most common database security flaws that is SQL Injection.
Use that text for your query, and then you can add your values to the query this way:
cmd.Parameters.AddWithValue("#grade", TxtGrade.Text.Trim);
cmd.Parameters.AddWithValue("#UserID", UserID);
//AND SO ON WITH OTHER PARAMETERS
Assumming cmd is your SqlCommand
Related
So my question actually has more than 2 parts but all linked with protecting my application against SQL injection.
Lately I am rebuilding my application to make it SQL injection proof. My application is written in VB.NET and I am using Parameters.Add to protect the queries.
UPDATE first question:
Found out that the NVARCHAR datatype is equal to the WChar datatype in OLEDB. When hovering over WChar it says in the description it is WSTR.
I am having a few questions though of which I cant find the answer on the web.
The first one, and I guess the easiest one is what the datatype in OleDB is of the NVARCHAR. When doing some research I found this link https://msdn.microsoft.com/en-us/library/ms130984.aspx which states that in OleDB the DBTYPE_WSTR datatype is the same as the NVARCHAR (which I am using in my t-SQL server). However when adding parameters in my VB application there is no such datatype available (WSTR). Some options are the VarChar, VarWChar, WChar, LongVarChar, LongVarWChar.
The question is, which one is the right one? I assume it is VarChar.
-------UPDATED UNTIL HERE-----
The second question is about how to handle parameters when a IF condition is involved in the query (see the example below).
sSQL1 = "SELECT [Omschrijving], [Nummer], [OrderType], [Orderdatum] FROM [Orders] WHERE [OrderDatum]>dateadd(""ww"",-4,GetDate()) "
If sOrderType <> "" Then
sSQL1 &= "AND ([OrderType]=""" & sOrderType & """)"
End If
sSQL1 &= "ORDER BY [Orders].[Nummer] DESC;"
lstOrder.Items.Clear()
Try
OpenConn()
cmd = New OleDbCommand(sSQL1, cn)
dr = cmd.ExecuteReader
While dr.Read()
lstOrder.Items.Add(dr("nummer") & " - " & dr("Omschrijving"))
End While
Catch
Debug.Print(sSQL1)
MsgBox("Error: " & sSQL1)
End Try
dr.Close()
CloseConn()
How should I rewrite this with using parameters? Do I need to instantiate the cmd = New OleDbCommand(sSQL1, cn) in the if condition together with the Parameters.Add ? But I guess this would also mean I have to open the connection earlier?
I thought about rewriting in something like this:
OpenConn()
sSQL1 = "SELECT [Omschrijving], [Nummer], [OrderType], [Orderdatum] FROM [Orders] WHERE [OrderDatum]>dateadd(""ww"",-4,GetDate()) "
If sOrderType <> "" Then
sSQL1 &= "AND ([OrderType]=?)"
cmd = New OleDbCommand(sSQL1, cn)
cmd.CommandType = CommandType.StoredProcedure
cmd.Parameters.Add("#OrderType", OleDbType.VarChar).Value = sOrderType
Else
cmd = New OleDbCommand(sSQL1, cn)
End If
sSQL1 &= "ORDER BY [Orders].[Nummer] DESC;"
lstOrder.Items.Clear()
Try
dr = cmd.ExecuteReader
While dr.Read()
lstOrder.Items.Add(dr("nummer") & " - " & dr("Omschrijving"))
End While
Catch
Debug.Print(sSQL1)
MsgBox("Error: " & sSQL1)
End Try
No idea if this works though (and for now I sadly can't test it).
Another question is: Do I need to use parameters for the dateadd (see query above) in the query as well? And if I do, how?
The last question is, when I am using the Parameters.Add, is it best to give a size value as well or is this not necessary?
Thank you in advance!
My answer to your first question that
I think this is the list of equal data-types you want:
SQL Server | OLEDB (ADO => ad+...)
-----------+---------------
char | Char
nchar | WChar
varchar | VarChar
nvarchar | VarWChar
text | LongVarChar
ntext | LongWVarChar
I have an SQL update command that I can't get to work. i want it to update the fields where the date is equal to the current date. It works for my INSERT and SELECT statements. But I get a missing operator error when using it for my Delete statement below.
Cmd.Connection = conn
Cmd.CommandText = "UPDATE tbl_Expenditure SET E_Stock =" & NewEStock & "," & "E_Total =" & ETotal & "WHERE [E_Date] = #" & thisMonth & "/" & Day & "/" & thisYear & "#;"
Cmd.ExecuteNonQuery()
Ive tried searching this site as well as others and can't seem to find an answer.
This is my error
Syntax error (missing operator) in query expression '95WHERE [E_Date] = #4/1/2015#'.
Thanks for any help
Using conn As New SqlConnection("connection string here"), _
cmd As New SqlCommand("UPDATE tbl_Expenditure SET E_Stock = #Stock, E_Total = #Total WHERE [E_Date] = #Date;", conn)
'Guessing at column types here
cmd.Parameters.Add("#Stock", SqlDbType.Int).Value = NewEStock
cmd.Parameters.Add("#Total", SqlDbType.Decimal, 8, 2).Value = ETotal
cmd.Parameters.Add("#Date", SqlDbType.DateTime).Value = New DateTime(thisYear, thisMonth, Day)
cmd.ExecuteNonQuery()
End Using
This fixes a HUGE security issue in the code, it has a performance benefit in allowing Sql Server to cache your query plan, and it solves your problem in that is makes it much easier to spot silly syntax mistakes like the missing space in front of the WHERE clause.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
I am trying to write a SQL statement in a VB application. In this case, I need to declare two variables to call other stored procedures. This code works when I run it in SSMS, but I am not sure how to do it in VB.
Statement:
DECLARE #NewIncidentNoteId NVARCHAR(15)
EXEC uspGetNextId #NewIncidentNoteId OUTPUT
INSERT INTO [dbo].[IncidentNotes]
([Id]
,[IncidentId]
,[TaskId]
,[VLevel]
,[NotesSourceType]
,[Notes]
,[LogDate]
,[LogTime]
,[LogTZ]
,[LogBy]
,[LogByName]
,[NotifyFlg]
,[ActivityDate]
,[ActivityTime]
,[ShowInReport])
VALUES()
(#NewIncidentNoteId
,'60Z3M'
,''
,'1'
,'EIRInvestigatorComment'
,'This is a TEST note.'
,'20150416'
,'10:10:10'
,'UTC'
,'12876'
,'USER, ADMIN'
,'False'
,'20150416'
,'12:13:13'
,'1'))
First of all, as others have said, the best option would be to actually add it to the database as a stored procedure. Then you could just execute the stored procedure via a simple ADO.NET command. However, if you insist on sending the entire SQL script as a command, there are several ways to get it as a string.
VB doesn't currently have great support for multi-line string literals (long-overdue support for that is being added in VB.NET 14 as part of Visual Studio 2015). There are several workarounds. See this other answer of mine for some good options. However, for something like this, you may want to look into reading the script from an embedded resource or an external script file.
Set cmd = New ADODB.Command
cmd.ActiveConnection = con
cmd.CommandType = adCmdStoredProc
cmd.CommandText = "empdetails"
cmd.Parameters.Append cmd.CreateParameter_
("empid", adVarChar, adParamInput, 6, str_empid)
Set rs = cmd.Execute
If Not rs.EOF Then
txt_firstname = rs.Fields(0)
txt_title = rs.Fields(1)
txt_address = rs.Fields(2)
End If
Set cmd.ActiveConnection = Nothing
this code show how to use SP in vb6 not sure which vb you use if it is VB.net then you can use ADO.net to do that
this link might be helpful too
http://www.codeproject.com/Articles/15222/How-to-Use-Stored-Procedures-in-VB
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I want to select table data in my page. Kindly provide a solution for my select query.
This is my code:
con.Open()
cmd = New SqlCommand("select name from wq where id='" + TextBox1.Text + "'", con)
dr = cmd.ExecuteReader
While dr.Read
TextBox2.Text = dr(0)
End While
dr.Close()
con.Close()
It looks like vb code if you want c# code then use following code
cmd = new SqlCommand("select name from wq where id='" + TextBox1.Text + "'", con);
con.Open();
dr = cmd.ExecuteReader();
dr.Read();
TextBox2.Text = dr[0].ToString();
dr.Close();
con.Close();
Started getting this error it seems since we upgraded to SQL Server 2008.
When inserting into the db and then returning the identity i get a 'Item cannot be found in the collection corresponding to the requested name or ordinal' error.
Here is the code:
SQL = "INSERT INTO PageFeatures(nPageFeatureFlagId,nPageFeatureFeatureId,nPageFeaturePageId) VALUES(" & nTemplateFlagId & "," & nFeatureId & "," & nPageId & "); SELECT SCOPE_IDENTITY() As nPageFeatureId;"
objrs.open SQL,objConn,1,1
nPageFeatureId = objrs("nPageFeatureId")
objrs.close
The insert is working as the record is in the db. It's not returning the id for some reason. It works fine and returns the id when running in SSMS. But ASP can't see the returned id so some reason.
Any help would be greatly appreciated!
You may have to try moving the recordset on? e.g.
SQL = "INSERT INTO PageFeatures(nPageFeatureFlagId,nPageFeatureFeatureId,nPageFeaturePageId) VALUES(" & nTemplateFlagId & "," & nFeatureId & "," & nPageId & "); SELECT SCOPE_IDENTITY() As nPageFeatureId;"
objrs.open SQL,objConn,1,1
objrs.NextRecordset
nPageFeatureId = objrs("nPageFeatureId")
objrs.close
Raj's comment about SQL injection is still relevant. :)
EDIT: Elaboration is that there are two recordsets in play here. The first is an empty one created by the insert statement, the second one is caused by everything after the semi-colon ;. This is the field you want. So initially, your objrs is attached to the first of its collection of recordsets (not rows in a recordset), you move to the NextRecordset - and you can then deal with that how you please.
Sorted:
SQL = "INSERT INTO PageFeatures(nPageFeatureFlagId,nPageFeatureFeatureId,nPageFeaturePageId) VALUES(" & nTemplateFlagId & "," & nFeatureId & "," & nPageId & ");"
objConn.execute(SQL)
Set oReturnValueRS = objConn.Execute("SELECT SCOPE_IDENTITY()")
nPageFeatureId = oReturnValueRS(0).Value
oReturnValueRS.close : set oReturnValueRS = nothing