double where statement in SQL and ASP - sql

I am a little lost on how to incorporate TWO Where in my sql statement in my asp.
I am trying to get the userID and password entered previously and compare it with what I have in my database created on SQL:
I think my problem comes from my double quotation and single quotation.
UserID is a number in my database and Password is a short text.
var mycon = new ActiveXObject("ADODB.Connection");
var myrec = new ActiveXObject("ADODB.Recordset");
mycon.Open("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\\Users\\Omnivox.mdb");
var txtpassword = Request.QueryString("txtpassword");
var txtuserID = parseInt (Request.QueryString("txtuserID"));
var sql;
sql = "SELECT UserID, UserPassword FROM UserOmnivox WHERE UserID=" +txtuserID+ " AND UserPassword='" + txtpassword + "';";
myrec.Open(sql, mycon);
thank you
UPDATE: It is still not working. The error massage is : no value given for one or more required parameters for the line myrec.Open(sql,mycon)

Change
sql = "SELECT * FROM UserOmnivox WHERE UserID=" +txtuserID "AND UserPassword="'+txtpassword';
to
sql = "SELECT * FROM UserOmnivox WHERE UserID=" +txtuserID + " AND UserPassword='"+txtpassword+"'";

If you'd done any kind of basic debugging, like LOOKING at the query string you're generating, you'd have seen this:
sql = "SELECT [..snip..] UserID=" +txtuserID "AND UserPassword="'+txtpassword
^^--- no space
^--- missing +
which produces
SELECT .... UserID=1234AND userPassword
^^---syntax error, no such field '1234AND'
And then, yes, your quotes are wrong too
sql = "SELECT ... UserID=" +txtuserID "AND UserPassword="'+txtpassword
^------------------^-- one string
^-----------------^-- another string
^---???
It should be
sql = "SELECT * FROM UserOmnivox WHERE UserID=" +txtuserID + " AND UserPassword='" + txtpassword + "';";

I find another more flexible solution is better. Sometimes based on conditions you have one where condition, in others you have zero, and in others you have two. If you go down these paths they don't solve that issue. The following does.....
Some sql query
where 1=1 -- ## A condition that will always be true and does nothing to your query.
and first optional where clause
and second optional where clause
This way if you don't have the first where clause in a given situation but you do have the second you are not missing the words "where". You always have the where and you optionally add any array of "and" parts to your where statement. 100% flexibility in this method works for all challenges. Plus it is easier to follow code once you get past the wtf is this 1=1 nonsense reaction.

Related

How to search into oracle database a row by chinese characters? vb.net

I have a problem when I try to extract a row from oracle Database with help by a string query.
If I try to search a row by normal characters, my query work, if I try to change with chinese characters my query doesn't found any row.
conn.Open()
cmd.Connection = conn
cmd.CommandText = "select DIRNAME from PROJECTINFO where UPPER(NAME) = UPPER('" + projFullName + "')"
cmd.CommandType = CommandType.Text
dr = cmd.ExecuteReader()
If dr.Read() Then
strProjRawDataSharePath = dr.Item("DIRNAME")
Else
dr.Close()
dr.Dispose()
End If
dr.Close()
dr.Dispose()
If I search my "projFullName" from query with "Default" (projFullName = "Defaults"), my query work grate, if I change with projFullName = "中文版测试", my query doesn't return any value, although, in my data base i have a project with name projFullName = "中文版测试".
You may want to consider using NLS_UPPER instead of UPPER.
NLS_UPPER is aware of language - specific rules etc, whereas UPPER will only apply to "english" characters, and (IRC) will translate these into english characters.
Running the below query will show you the data side-by-side and will potentially highlight the issue for you.
select UPPER(Input.ChineseText), NLS_UPPER(Input.ChineseText)
from (select '中文版测试' as ChineseText from dual) Input;
Alternatively, it may be worth considering if UPPER is needed - Using UPPER will mean that no indexes are used in the query execution - but this is off topic for this question.
Please, use N modifier as shown below to work with unicode strings:
cmd.CommandText = "select DIRNAME from PROJECTINFO where NAME = N'" + projFullName + "'"
Hope this helps!
Check NLS_SORT for chinese which is what you might need
Linguistic Sorting and String Searching
select DIRNAME from PROJECTINFO where NLS_UPPER(NAME, 'NLS_SORT =
SCHINESE_PINYIN_M') = '中文版测试'
I'd do that:
'" + projFullName + "'
" + 'projFullName' + "
"select DIRNAME from PROJECTINFO where UPPER(NAME) = UPPER(+'中文版测试'+)"
Test this without defining, directly into code, as Quotation marks in VB code seem to be incorrect in there, they would end Oracle SQL Query.
select UTL_I18N.RAW_TO_NCHAR(UTL_I18N.STRING_TO_RAW(NAME), 'ZHS16CGB231280') As NAME, UTL_I18N.RAW_TO_NCHAR(UTL_I18N.STRING_TO_RAW(DIRNAME), 'ZHS16CGB231280') As DIR FROM PROJECS"
This query help me to convert de condification from oracle to Chinese characters

hash password different between query text and query parameter

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'"

Can someone clarify this SQL command

I saw this in some ASP code and didnt understand the last line, specifically all the apostrophies and quotation marks between Name= and AND. what is being appended? why do we need both?
uName = getRequestString("UserName");
uPass = getRequestString("UserPass");
sql = "SELECT * FROM Users WHERE Name ='" + uName + "' AND Pass ='" + uPass + "'"
The code is building a query that looks like this:
SELECT * FROM Users WHERE Name = 'foo' AND Pass = 'bar'
It passes in the text from the uName and uPass variables into the query string.
This is very dangerous though - it's an open door for SQL Injection.
That is very simple, you have the start of a string sentence with double quotes. Double quotes indicate the start and the end or part of a string.
for example, if you have
sql ="SELECT * FROM USERS"
your sentence takes all the value; if you have:
sql = "SELCT * FROM USERS"
whereSentence = " WHERE id = 1"
wholeSql = sql + whereSentence
with the + (plus symbol) you are concatening all the string.
With the simple quotes you are adding the simple quote in the string and concatening the other parts of the sentence.
For example if
uName = 'John' and uPass = 'McDonals'
sql = "SELECT * FROM Users WHERE Name ='" + uName + "' AND Pass ='" + uPass + "'"
your final sentence should be
SELECT * FROM Users WHERE Name = 'John' And Pass = 'McDonals'.
Is a simple way to say that the name is John McDonals as String, but the parameters are variables, depending the request
The first quotation (') mark is in the SQL lateron. The second quotation mark ("), marks the String literal for ASP.
After parsing, the query will be something like:
SELECT * FROM Users WHERE Name ='name' AND Pass ='password'
Which is why you need the ', because your intention is to give the DBMS a string.
This code is building a complete string for the SQL request. Presumably, this is connected to a webpage that asks for the username and password to be submitted in a block.
The uName and uPass strings will be set to something like this:
uName = "John";
uPass = "qwerty";
When the sql string gets created, the SQL query needs to put quotes around the string values, so the final query will look like this:
sql = "SELECT * FROM Users WHERE Name ='John' AND Pass ='qwerty'"
If you wrote:
SELECT x from y where y.name = martin
you would get an error. You need apostrophes to denote a string, like so:
SELECT x from y where y.name = 'martin'
Quotes are because someone appends a variable to a string, then appends another string and first character of that string, the apostrophe, is a closing apostrophe after my martin example.
Don't do that though, I mean don't append variables to strings, unless you know what you are doing. Use parameterized queries.

VB.NET 2010 & MS Access 2010 - Conversion from string "" to type 'Double' is not valid

I am new to VB.Net 2010. Here is my problem: I have a query that uses a combo box to fetch many items in tblKBA. All IDs in the MS Access database are integers. The combo box display member and value member is set to the asset and ID of tblProducts.
myQuery = "SELECT id, desc, solution FROM tblKBA WHERE tblKBA.product_id = '" + cmbProducts.SelectedValue + "'"
In addition to getting items from the KBA table, I want to fetch the department details from the department table, possibly done in the same query. I am trying to do it in two separate queries.
myQuery = "select telephone, desc, website from tblDepartments where tblDepartments.product_id = tblProducts.id and tblProducts.id = '" + cmbProducts.SelectedValue + "' "
All help will be appreciated!
Change the '+' to a '&' then the compiler would be happy.
try adding .toString to cmbproducts.selectedvalue or do "tblKBA.product_id.equals(" & cmbProducts.selectedValue.toString & ")"
1.) Don't use string concatenation to build your query. Use parameters.
2.) I am guessing that tblKBA.product_id is a double and not a string, so don't put quotes around it.
myQuery = "SELECT id, desc FROM tblKBA WHERE tblKBA.product_id = ?"
3 things. Test your value before building the select statement. Second, Use .SelectedItem.Value instead of .SelectedValue. Third, protect yourself from sql injection attack. Use parameters, or at the very least check for ' values.
If IsNumeric(cmbProducts.SelectedItem.Value) = False Then
'No valid value
Return
End If
myQuery = String.Format("SELECT id, desc FROM tblKBA WHERE tblKBA.product_id = {0}", cmbProducts.SelectedItem.Value.Replace("'", "''"))

Matching text string on first letter in SQL query

SAMPLE CODE:
Dim sql As String = "SELECT * FROM " + tblName + " WHERE needsTranslation = 'True' AND dataText LIKE " & "'" & alpha & "%" & "'" & " ORDER BY dataText;"
da = New SqlDataAdapter(sql, strConnection)
OP:
I would like to create a SQL query that returns all records when the first letter of a string matches my variable. I am coding this in an ASP.net code behind page in vb.net.
SELECT * FROM " + tblName + " WHERE textData = ' & alpha & "
In this exmample textData is a string of text and alpha is a single letter a through z or A through Z.
I don't need the criteria to be case sensitive, but I do need only the first letter of textData to match alpha.
I have tested the LIKE comparator and it does not return all records that begin with alpha.
What is the best way to do this? Any and all help will be appreciated.
thanks again,
The LIKE operator is what you'd want to use, but you have to use the % wildcard character like so:
SELECT * FROM MyTable WHERE textData LIKE 'a%'
SQL has sub-string operator SUBSTR() or SUBSTRING()
select * from tableName where substr( textData ) in ( 'A', 'B', 'C', ... );
I couldn't add to the comments on one of the other posts, but I'll strongly second the need to use a parameterized query for these reasons (you can include usage of the like operator with the wildcard % like the other answer correctly summarized to answer your question):
It will protect you from making mistakes with single quotes, especially if the user enters a search string that includes them
(they will cause your query to fail).
It protects you from SQL injection exploits. Example, a user were able to input the value of the variable "alpha" in the above
example they could enter something like:
'; DELETE FROM ;
If the user you were using had excessive database rights, they could
wreak all kinds of havoc (or they could potentially get access to
data they shouldn't have access to).