Quoting problems with a string query in sql - 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

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.

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.

SQL - Using a prepared statement for the FROM clause?

Is it possible to use a prepared statement for the FROM clause?
I'm trying to do this:
PreparedStatement preStmType = conn.prepareStatement("SELECT * FROM ? WHERE article_id = ?");
preStmType.setString(1, rsetArticle.getString(5));
preStmType.setInt(2, rsetArticle.getInt(1));
It does not seem to work. When I remove the argument for the FROM clause and use it only in the where, it works, but I would like to generate the FROM dynamically too.
Nope, you can't
Prepared statements supports data literals only.
Speaking of this particular case, why do you want to generate fieldlist dynamically? If you don't know what field you need - just select all and then pick one from the returned row
Are you using Java?
How about trying this:
String qryStr = "SELECT * FROM "+rsetArticle.getString(5)+" "
qryStr =qryStr + "WHERE article_id = ?"
PreparedStatement preStmType = conn.prepareStatement(qryStr);
preStmType.setInt(1, rsetArticle.getInt(1));

SQL Like statement not working in Visual Basic

Dim strText As String = tbRefine.Text
Dim sql As String = "SELECT user_name,forename,surname,game_cash,reg_group FROM tblGame WHERE user_name LIKE '" + strSearchText + "' & '*'"
Dim dsRefine As New DataSet
GetDataset(sql, "tblGame", dsRefine)
MsgBox(dsRefine.Tables("tblGame").Rows(0).Item(2).ToString)
This is not working, it crashes and says there is nothing in the dataset.
I know the dataset function works as its worked successfully before.
When i print out the sql statement into microsoft access it works fine. What am i doing wrong
Try this:
"SELECT user_name,forename,surname,game_cash,reg_group
FROM tblGame
WHERE user_name LIKE '%" + strSearchText + "%'"
Try to use the RTRIM() function in your line:
Dim sql As String = "SELECT user_name,forename,surname,game_cash,reg_group
FROM tblGame
WHERE RTRIM(user_name) LIKE '" + strSearchText + "' & '*'"
What about leading or trailing % symbols in your like?
At the moment you will end up with a where clause like:
LIKE 'searchtext''*'
which looks a bit odd (I assume SQL server?).
It's wiser to use SQL parameters as your method is open to SQL injection. The link below will help with how to format the SQL statement. I would also suggest doing it via a store procedure, but hats optional...
http://forums.asp.net/t/1256985.aspx
I think there's one more thing to be mentioned:
the "*" wildcard character works for the "Like" operator in VB/VBA/MS-Access, but not in T-SQL.
The correct wildcard character for the "Like" operator in T-SQL is "%".
That's why this T-SQL statement:
Select... WHERE ... LIKE 'sText*'
returned no data without any syntax error in MS-SQL(using T-SQL), but works in MS-Access.

Ole DB statement runs in Access but not in Visual Studios

I have the following statement and it returns my desired result in Access however in Visual Studio, I receive an error saying "; expected", what could be the problem?
var query = "SELECT Count(*) FROM usersTable WHERE (((usersTable.[uDateCreated]) Between DateAdd("d",-2,Now()) And Now()))";
You need to escape your quotes inside your string:
" .. Between DateAdd(\"d\",-2 .. "
^ ^ escape the quotes
You're using a quotation mark in your query, which is ending the string. Use apostrophes around d instead:
var query = "SELECT Count(*) FROM usersTable WHERE (((usersTable.[uDateCreated]) " & _
"Between DateAdd('d',-2,Now()) And Now()))"
Specifically:
DateAdd('d',-2,Now())
I think your problem is that you have " (quotes) in your string without escaping them. I donut know which language you are using, but for many you escape with \ (backslash), then your string would read DateAdd(\"d\",