Can someone clarify this SQL command - sql

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.

Related

double where statement in SQL and ASP

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.

Quoting problems with a string query in sql

I am trying to make a query using the LIKE operator
String camp= nomePesquisa.getValue();
String ql = "select from pessoal where nome_Pessoa like ""'%"+camp+"%'" "";
and it gives the following error
Multiple markers at this line
- Syntax error on token """", delete this
token
There is a basic mistake that causes all the issues: you don't use parameterized queries. This will a) secure your code against SQL injection, and b) make your SQL easier to write.
In my preferred programming language, C#, it would look like this:
"select from pessoal where nome_Pessoa like #name"
Where #name is the name of the parameter you have to pass in.
It seems according to your code you are using Java. This might help you in that case.
try this
String ql = "select * from pessoal where nome_Pessoa like '%"+camp+"%'+ ";
you've put to many quetas, but if you need them to bee in string for some reason, you should escape them \".
P.S. you forgot to type what you wanna select
Select * FROM table or SELECT col1,col2 FROM TABLE
P.S.S. don't put parameters in query like that, because it is an easy way for Query Injection.
Remove all the " from that line:
String ql = "select from pessoal where nome_Pessoa like '%"+camp+"%'+ ";
You aren't concatenating anything there.
Please use the following to remove the unnecessary quotes:
String ql = "select from pessoal where nome_Pessoa like '%"+camp+"%'+ ";
Also, you can use some escape characters.
You can simply write it as
String ql = "select from pessoal where nome_Pessoa like '%" + camp + "%'";
Change the following code
String ql = "select from pessoal where nome_Pessoa like '%"+camp+"%'+ ";
You missed the plus operator

Sql Where Statement

I'm trying to compare two variables that I'm getting from json service with a database that I have in my app. I tried to hard coding it and it worked
Statement st = tmsDB.createStatement(
"SELECT * FROM ObjectTexts WHERE programID ='AAA' AND objName ='BBB'");
But when I tried to do this `
Statement st = tmsDB.createStatement(
"SELECT * FROM ObjectTexts WHERE programID="+ JsonProgramID +"AND objName ="+JsonobjName);
it didn't work.
Any ideas?
FROM ObjectTexts WHERE programID='"+ JsonProgramID +"' AND objName =' "+JsonobjName +"'"
If you observe the hardcoded query your parameters are inside single quotes, but dynamic one missing single quotes.
In SQL all String/Varchar should be inside single quote.
Note: These raw queries are highly vulnerable for SQL injection.
The BlackBerry API supports the normal create, prepare, bind, execute semantics:
Statement st = tmsDB.createStatement( "SELECT * FROM ObjectTexts WHERE programID=? AND objName = ?");
st.prepare();
st.bind(1, JasonProgramID);
st.bind(2, JsonobjName);
Cursor c = st.getCursor();
...
You seem to be missing spaces and single quotes. Try this:
Statement st = tmsDB.createStatement("SELECT * FROM ObjectTexts WHERE programID= '"+ JsonProgramID +"' AND objName = '"+JsonobjName+"'");

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).