Sql Where Statement - sql

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+"'");

Related

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

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.

SQL : how to use IN keyword with prepared statement for range replacement using Java

String sql = "select * from file_repo_index where id in (?)";
PreparedStatement ps = conn.prepareStatement(sql);
ps.setString (1, toCommaSeparatedList(repoIdList));
ResultSet result = ps.executeQuery();
public static String toCommaSeparatedList(Collection col);
I have to use the query as
select * from file_repo_index where id in ( 1,2,3,4 )
But it gives following error in executeQuery() statement
java.sql.SQLException: Conversion failed when converting the nvarchar value '213304,213305,213307' to data type int.
I can use it like
String sql = "select * from file_repo_index where id in ("+toCommaSeparatedList(repoIdList)+")";
Statement ps = conn.createStatement();
ResultSet result = ps.executeQuery(sql);
But I want to use the PrepareStatment method. How can I do it. ??
You should create your prepare statement placeholders based on your values, for instance:
String sql = "select * from file_repo_index where id in (";
//append ?, in above sql in a loop
//Then prepare statement.
This will involve a bit of extra coding, but i think this is the only way to force using PreparedStatement.
If You want to use IN keyword then inside the brackets you have to put like
('213304','213305','213307')
as seperate variables and dont combine in a single "single quotes the entire values" and also in the select statement
String sql = "select * from file_repo_index where id in ("+toCommaSeparatedList(repoIdList)+")";
Change the double quotes to single and try
('+ toCommaSeparatedList(repoIdList) +')";