hash password different between query text and query parameter - sql

i want to ask is it different to hashbytes by query and parameter ?
my code is
.CommandText = "update table.pass " _
& "set password = convert(varchar(12),HASHBYTES('MD5','" & TextEdit3.Text.ToUpper.ToString & "'),2) where userid='" + USER_ID + "'"
my second code is
.CommandText = "update table.pass " _
& " set password = convert(varchar(12),HASHBYTES('MD5',#pass),2) where userid=#userid"
.Parameters.AddWithValue("#pass", TextEdit3.Text.ToUpper.ToString)
.Parameters.AddWithValue("#userid", USER_ID)
for now iam using the first code, and i know it's wrong due to sql injection. so i want to use the second code. but the result was different from the first code.
what i want is, how do i use parameter but the result is same with the first code, because my predecessor use the first one

I believe that AddWithValue assumes nvarchar for String data. It is generally recommended to use Add and specify the data type yourself when there is any doubt about which data type will be used. If you do that and specify VarChar then you should get the same result.
EDIT: Either that or put an 'N' prefix in the first code, i.e.
"set password = convert(varchar(12),HASHBYTES('MD5',N'"

Related

Run one MS Access SQL script on a particular Table chosen by user

I have a MS Access 2016 database (*.accdb) with 20+ Tables. Fields in each of them vary slightly from Table to Table. I've no VBA experience, so I'm sticking only to the SQL query below (redacted).
SQL script
myvar below is the parameter I'd like to be prompted when the script is run so that I enter the Table I want the changes applied to.
PARAMETERS
[myvar] TableID;
UPDATE
[myvar]
INNER JOIN
Excel_Data ON [myvar].[Part Number] = Excel_Data.[Part Number]
SET
[myvar].[Value] = '?',
[myvar].Description = Excel_Data.Description,
[myvar].[Ref] = '?'
.
.
.
WHERE
[myvar].Description Is Null;
Output
Error message:
Too few parameters. Expected 0.
What I need
I prefer a solution for above in a SQL script form as above, not involving VBA, preferably. I'd like to enter the Table name when prompted so the script knows which table to UPDATE. FYI: The PARAMETERS work when it is not a Table as I've shown in my script above.
Help/advise is highly appreciated.
EDIT 1
Since it seems not possible to use parameters as Table names, could you suggest a VBA solution? A sample code, perhaps?
As said in the comments, you can't really solve this without VBA.
You can store your SQL query in a string, and use a placeholder to indicate the tablename. Then get the tablename using an inputbox and replace the placeholder with the tablename.
Dim sqlString As String
sqlString = "UPDATE [%Placeholder%] " & vbCrLf & _
"INNER JOIN Excel_Data ON [%Placeholder%].[Part Number] = Excel_Data.[Part Number] " & vbCrLf & _
"SET [%Placeholder%].[Value] = '?', " & vbCrLf & _
...
"WHERE [%Placeholder%].Description Is Null;"
sqlString = Replace(sqlString, "%PlaceHolder%", InputBox("Enter a tablename"))
CurrentDb.Execute sqlString
In a more mature solution, I'd create a form with a combobox containing all available table names, and add a function to sanitize tablenames (replace "]" with "]]")

Vb 2015 query with parameters not working

I already used parametrized queries with no problem, but today I'm stuck on an error that I cannot debug.
This is my working query
cmd.CommandText = "select idcliente, ragsociale from Clienti where idcliente =" & strName & " or codiceamministrazione='" & strName & "' or piva='" & strName & "' or codfisc='" & strName & "'"
The same, but with parameter, not working
cmd.CommandText = "select idcliente, ragsociale from Clienti where idcliente = #Cliente or codiceamministrazione=#Cliente or piva=#Cliente or codfisc=#Cliente"
cmd.Parameters.AddWithValue("#Cliente", strName)
I use this in an autocomplete procedure that shows the name of a client based on internal id or on commercial license number (and other similar codes). On the db a client record can have all the code fields compiled or just 1.
With the non-parametrized query the autocomplete suggestion pop-up,with the parametrized one nothing shows. No errors either.
EDIT:
using this
cmd.Parameters.Add("#Cliente", SqlDbType.VarChar)
cmd.Parameters("#Cliente").Value = strName
now another query (omitted before for semplicity) in the same function works, but, strange enough, the one for what I did this question don't.
Working:
cmd.CommandText = "select idcliente, ragsociale from Clienti where ragsociale like '%'+#Cliente+'%' or codiceamministrazione=#Cliente"
Still not Working:
cmd.CommandText = "select idcliente, ragsociale from Clienti where idcliente = #Cliente or piva=#Cliente or codfisc=#Cliente"
In your original query, when testing against idcliente, you treat strName as a number (no quotes round it), but for all the other fields you treat it like a string. So you're implying it could potentially contain a number or a string. This is problematic, if you type a number, and the parameterised version of the query now treats it like a string in all cases, then it won't match the numeric value of idcliente in the DB and therefore you may get no results.
To clarify: if your input is a number, but your query thinks it's a string (because of the data type in the param), it will not match against any numeric field in the database. 12345 != "12345".
You need to define separate parameters for these scenarios. You can pass the same value into them, but in one case set the parameter's datatype to varchar and in the other case to int (you might need to check if the value can be parsed as a number before you do this, otherwise it will likely crash. In that case just set it null or 0 or something that won't make an accidental match).

Inserting Single/double type to DB using VBA in access

I need some help with an issue that is doing my head in.
I need to update a database in access and its been working fine operating with Long and Integers.
Look at this code.
sql = "UPDATE DBNAME SET Long_Field = " & Long_Variable & " WHERE ID = " & id
DoCmd.SetWarnings (False)
DoCmd.RunSQL sql
This code runs flawlessly, it takes a long variable and puts it into the correct field which is set as Long.
However, if I want to populate a single/double field (ive tried both)
sql = "UPDATE DBNAME SET Double_Field = " & double_Variable & " WHERE ID= " & id
DoCmd.SetWarnings (False)
DoCmd.RunSQL sql
I keep getting Run-Time error 3144: Syntax error in update statement.
I can literally just switch out the field name and the variable name and the code runs flawlessly, but as soon as i try to send a double value, for example (5,8), to a field in the table that is set to double, it gives me this error.
Anyone?
I assume that you want a dot as decimal separator in your string.
The conversion from double to string is done using the separator from the system locale settings so in your case a comma.
This means that
double_variable = 5.8
sql = "... " & double_variable & " ..."
will produce ... 5,8 ... in the sql variable.
The easiest way to fix that is to use
"..." & Replace(CStr(double_variable), ",", ".") & "..."
This will replace all , with .. I put the CStr there to make sure it gets converted to a string first. It will also work if the system locale changes since nothing will happen if there is no ,. The only caveat is that if for some reason the conversion inserts 1000s separators it will fail but that would only be relevant in other circumstances as I don't think CStr will ever do that.
The current answer is not the easiest, neither the simplest.
The universal method is to use Str as it always returns a dot as the decimal separator:
sql = "UPDATE DBNAME SET Double_Field = " & Str(double_Variable) & " WHERE ID = " & id & ""

Parameterized field name

I was thinking if this will work:
Dim query As String = "UPDATE tblPiglets SET #to=#todate, CurrentLocation=#to" & _
" WHERE Week=#week AND SowOrder=#so AND PigletNumber=#pig"
But I caught Cannot update #to field lol
The #to is a variable in which I thought would work the same its value though its worth a try. Its value is dependent on a user input, so, is there any other way to do that?
Or this? (not sure if this will work though):
Dim to As String = "foo"
Dim query As String = "UPDATE tblPiglets SET " & to & "=#todate, CurrentLocation=#to" & _
" WHERE Week=#week AND SowOrder=#so AND PigletNumber=#pig"
It is always preferable to use parameters to insert user input into SQL code but parameters can only be used for values, not identifiers. Think of SQL parameters the same as parameters in a VB method. You can't use a method parameter to specify a property or method to use and you can't use a SQL parameter to specify a column or table.
You have no choice but to use string concatenation but doing so opens you up to SQL injection, so make absolutely sure that the user cannot insert arbitrary SQL code. If it's a column name then they should have to select it from a list that you have retrieved from the database itself, so that you are guaranteed that it's a valid column.
I have used option 2 to make it work.
Dim to As String = "foo"
Dim query As String = "UPDATE tblPiglets SET " & to & "=#todate, CurrentLocation=#to" & _
" WHERE Week=#week AND SowOrder=#so AND PigletNumber=#pig"
But it would be nicer if I can get the same result if I will be using the first option. thanks

parameterized query not working in VB

statement = "SELECT OrderID, (SELECT VendName FROM Vendors WHERE Vendors.VendorID = Orders.VendorID) " &
",OrderDt, RcvdDt, OrderTotal " &
"FROM Orders " &
"WHERE VendName=? " &
"ORDER BY OrderDt DESC"
Dim cmd As New OleDbCommand(statement, connection)
cmd.Parameters.AddWithValue("VendName", txtVendorFilter.Text)
Dim reader As OleDbDataReader = cmd.ExecuteReader(CommandBehavior.Default)
I was trying to do this before by simply concatenating the textbox value right into the SQL and I was getting a "No values given for required parameters", and read that that I should use parameterized queries instead. So I tried this and it doesn't give me any errors, but the reader never has anything in it. I've never used parameterized queries before, so I'm a bit lost as to why this isn't working.
Edit:
I've changed the above code to account for OLEDB from what I briefly read on how it should work, and it's giving me the "no values given for required parameters" again.
One problem is here:
"WHERE VendName='#x' " &
Drop the ' marks - the parameterization will take care of this for you:
"WHERE VendName= #x " &
Using the ' in the query means that '#x' is treated as a string type, not a parameter name.
Additionally, since you are using OleDb, names parameters are not supported. You need to use ? to signify a parameter in the query:
"WHERE VendName= ? " &