I have stuck with the simplest SQL query in java - java

I can't find the correct syntax of the following query in java,please help me.
String st = "SELECT COUNT('"+id+"') FROM '"+selected_table+"' ";
String st = "SELECT COUNT('"+id+"') FROM '"+selected_table+"'";
I think that the mistake is how to end the query...
Since I got the error Check the manual that corresponds to your MySQL server version for the right syntax to use near ''Customer'' at line 1
when I choose Customer table

You want to use backticks instead of single quotes around your object names.
String st = "SELECT COUNT(`"+id+"`) FROM `"+selected_table+"` ";

Table names should be surrounded by tick marks (`), not single quotes (')
String st = "SELECT COUNT('"+id+"') FROM `"+selected_table+"`";
^ use tick marks ^

What are the values of id and selected_table? What is the actual query string that is sent to the database?
Also, it's rarely a good idea to manually build a query like this using string concatenation. This makes it very easy for a bug to result in a gaping security hole, and it's a lot more difficult (and risky) to try to secure this approach than it is to just do it right.

Looks from your query that you are enclosing your id and selected_table in single quotes... For example, SELECT COUNT('ID') FROM 'CUSTOMER' which is wrong. should be in backtics `` or nothing...

Related

preparestatement with name [duplicate]

I was wondering if there was any way to specify returned column names using prepared statements.
I am using MySQL and Java.
When I try it:
String columnNames="d,e,f"; //Actually from the user...
String name = "some_table"; //From user...
String query = "SELECT a,b,c,? FROM " + name + " WHERE d=?";//...
stmt = conn.prepareStatement(query);
stmt.setString(1, columnNames);
stmt.setString(2, "x");
I get this type of statement (printing right before execution).
SELECT a,b,c,'d,e,f' FROM some_table WHERE d='x'
I would, however, like to see:
SELECT a,b,c,d,e,f FROM some_table WHERE d='x'
I know that I cannot do this for table names, as discussed
here, but was wondering if there was some way to do it for column names.
If there is not, then I will just have to try and make sure that I sanitize the input so it doesn't lead to SQL injection vulnerabilities.
This indicates a bad DB design. The user shouldn't need to know about the column names. Create a real DB column which holds those "column names" and store the data along it instead.
And any way, no, you cannot set column names as PreparedStatement values. You can only set column values as PreparedStatement values
If you'd like to continue in this direction, you need to sanitize the column names (to avoid SQL Injection) and concatenate/build the SQL string yourself. Quote the separate column names and use String#replace() to escape the same quote inside the column name.
Prepare a whitelist of allowed column names. Use the 'query' to look up in the whitelist to see if the column name is there. If not, reject the query.
For MySQL prepared statements with NodeJS (mysqljs/mysql), what you need to know is that ? is for values, but if you need to escape column names, table names etc, use ?? instead.
Something like this will work:
SELECT ??, ??, ?? FROM ?? WHERE ?? < ?
Set values to ['id', 'name', 'address', 'user', 'id', 100]
I think this case can't work because the whole point of the prepared statement is to prevent the user from putting in unescaped query bits - so you're always going to have the text quoted or escaped.
You'll need to sanitize this input in Java if you want to affect the query structure safely.
Use sql injection disadvantage of Statement Interface as advantage.
Ex:
st=conn.createStatement();
String columnName="name";
rs=st.executeQuery("select "+ columnName+" from ad_org ");
public void MethodName(String strFieldName1, String strFieldName2, String strTableName)
{
//Code to connect with database
String strSQLQuery=String.format("select %s, %s from %s", strFieldName, strFieldName2, strTableName);
st=conn.createStatement();
rs=st.executeQuery(strSQLQuery);
//rest code
}
Below is the solution in java.
String strSelectString = String.format("select %s, %s from %s", strFieldName, strFieldName2, strTableName);

How to compare utf8 text in mysql query using java

I have a problem while selecting from a table containg data in utf-8 format in MySQL using java, in the WHERE clause I need to compare if a column value equals to a java String but they don't match
"Select age from student where name = '"+stringVariable+"';"
the stringVariable can sometimes be in arabic so in this case they don't match
The database is utf8mb4 and the connection also between java and database is utf_8 and I dont have a problem while inserting or just selecting data but the problem occurs while comparing
I tried to convert the string like this and it also didnt match
byte[] b = stringVariable.getBytes("UTF-8");
String str = new String(b,"UTF-8");
So anyone has any solution for that ?!
Thank you in advance
Use parameters. The driver should then encode them correctly according to the connection properties.
PreparedStatement statement = connection.prepareStatement(
"select age from student where name = ?");
statement.setString(1, stringVariable);
In addition, this also correctly escapes special SQL characters (like single quotes).
You shouldn't have to transform anything. The driver takes care of everything. Try using a prepared statement rather than string concatenation. This will have the additional advantage of avoiding SQL injection attacks, and make sure your statement works even if the string variable contains a quote.
I solved this problem it was not only related with the database query but I get the string from ajax request so I had to decode it from utf8 first and then get the parameter value using
URLDecoder.decode(request.getQueryString(), "UTF-8")
and then pass it to the query and I used prepared statement which encodes it according to the connection properties as you mentioned
Thank you

SQL exception preparing query with ORMLite

I am using an ORM (ORMlite) and all my calls are going well until I get the following error.
Exception in thread "main" org.h2.jdbc.JdbcSQLException: Syntax error in SQL statement "
SELECT * FROM ""STORIES"" WHERE ""TITLE"" = 'Deepcut case leads 'NOT FOLLOWED[*]'' "; SQL statement:
SELECT * FROM Stories WHERE title = 'Deepcut case leads 'not followed'' [42000-152]
at org.h2.message.DbException.getJdbcSQLException(DbException.java:327)
at org.h2.message.DbException.get(DbException.java:167)
at org.h2.message.DbException.get(DbException.java:144)
at org.h2.message.DbException.getSyntaxError(DbException.java:179)
at org.h2.command.Parser.getSyntaxError(Parser.java:480)
at org.h2.command.Parser.prepareCommand(Parser.java:229)
at org.h2.engine.Session.prepareLocal(Session.java:426)
at org.h2.engine.Session.prepareCommand(Session.java:374)
at org.h2.jdbc.JdbcConnection.prepareCommand(JdbcConnection.java:1093)
at org.h2.jdbc.JdbcPreparedStatement.(JdbcPreparedStatement.java:71)
at org.h2.jdbc.JdbcConnection.prepareStatement(JdbcConnection.java:601)
at com.j256.ormlite.jdbc.JdbcDatabaseConnection.compileStatement(JdbcDatabaseConnection.java:83)
at com.j256.ormlite.stmt.mapped.MappedPreparedStmt.compile(MappedPreparedStmt.java:44)
at com.j256.ormlite.stmt.StatementExecutor.buildIterator(StatementExecutor.java:169)
at com.j256.ormlite.stmt.StatementExecutor.query(StatementExecutor.java:119)
at com.j256.ormlite.dao.BaseDaoImpl.query(BaseDaoImpl.java:189)
I'm confused as to whats going wrong. I am calling the search from these lines:
// get our query builder from the DAO
QueryBuilder<Story, Integer> queryBuilder = StoryDao.queryBuilder();
// the 'title' field must be equal to title (a variable)
queryBuilder.where().eq(Story.TITLE_FIELD_NAME, title);
// prepare our sql statement
PreparedQuery<Story> preparedQuery = queryBuilder.prepare();
// query for all stories that have that title
List<Story> accountList = StoryDao.query(preparedQuery);
Syntax error in SQL statement " SELECT * FROM ""STORIES"" WHERE ""TITLE""...
#bemace is correct that there seem to be quotes in the title that is screwing up the escaping of strings generated by the query.
In ORMLite, you should use the SelectArg feature which will generate a query with SQL ? arguments and then pass the string to the prepared statement directly.
See the documentation on the SelectArg. With it, you'd do something like:
QueryBuilder<Story, Integer> queryBuilder = StoryDao.queryBuilder();
SelectArg titleArg = new SelectArg();
queryBuilder.where().eq(Story.TITLE_FIELD_NAME, titleArg);
PreparedQuery<Story> preparedQuery = queryBuilder.prepare();
titleArg.setValue(title);
List<Story> accountList = StoryDao.query(preparedQuery);
I'm kind of guessing but it looks like there's a problem with the value in the title field, maybe an unescaped quote mark?
I'm not familiar with ORMLite but title = 'Deepcut case leads 'not followed'' doesn't look right. Should probably be "Deepcut case leads 'not followed'" or 'Deepcut case leads \'not followed\'' or some such.
The correct syntax for the statement would be:
SELECT * FROM Stories WHERE title = 'Deepcut case leads ''not followed'' ';
Note the duplicated single quotes inside the string literal.
You will need to tell your ORM layer to follow the ANSI SQL rules for literals.
The exception says that there is some syntactical problem with your generated SELECT statement. Can you print out the generated query? Doing that might help you pin down the exact issue here.
EDIT: Looking closely at your trace shows that string escaping is not handled properly here. Is this your own QueryBuilder? Also, as per this link, are you using SelectArg or directly setting the title?

Variable column names using prepared statements

I was wondering if there was any way to specify returned column names using prepared statements.
I am using MySQL and Java.
When I try it:
String columnNames="d,e,f"; //Actually from the user...
String name = "some_table"; //From user...
String query = "SELECT a,b,c,? FROM " + name + " WHERE d=?";//...
stmt = conn.prepareStatement(query);
stmt.setString(1, columnNames);
stmt.setString(2, "x");
I get this type of statement (printing right before execution).
SELECT a,b,c,'d,e,f' FROM some_table WHERE d='x'
I would, however, like to see:
SELECT a,b,c,d,e,f FROM some_table WHERE d='x'
I know that I cannot do this for table names, as discussed
here, but was wondering if there was some way to do it for column names.
If there is not, then I will just have to try and make sure that I sanitize the input so it doesn't lead to SQL injection vulnerabilities.
This indicates a bad DB design. The user shouldn't need to know about the column names. Create a real DB column which holds those "column names" and store the data along it instead.
And any way, no, you cannot set column names as PreparedStatement values. You can only set column values as PreparedStatement values
If you'd like to continue in this direction, you need to sanitize the column names (to avoid SQL Injection) and concatenate/build the SQL string yourself. Quote the separate column names and use String#replace() to escape the same quote inside the column name.
Prepare a whitelist of allowed column names. Use the 'query' to look up in the whitelist to see if the column name is there. If not, reject the query.
For MySQL prepared statements with NodeJS (mysqljs/mysql), what you need to know is that ? is for values, but if you need to escape column names, table names etc, use ?? instead.
Something like this will work:
SELECT ??, ??, ?? FROM ?? WHERE ?? < ?
Set values to ['id', 'name', 'address', 'user', 'id', 100]
I think this case can't work because the whole point of the prepared statement is to prevent the user from putting in unescaped query bits - so you're always going to have the text quoted or escaped.
You'll need to sanitize this input in Java if you want to affect the query structure safely.
Use sql injection disadvantage of Statement Interface as advantage.
Ex:
st=conn.createStatement();
String columnName="name";
rs=st.executeQuery("select "+ columnName+" from ad_org ");
public void MethodName(String strFieldName1, String strFieldName2, String strTableName)
{
//Code to connect with database
String strSQLQuery=String.format("select %s, %s from %s", strFieldName, strFieldName2, strTableName);
st=conn.createStatement();
rs=st.executeQuery(strSQLQuery);
//rest code
}
Below is the solution in java.
String strSelectString = String.format("select %s, %s from %s", strFieldName, strFieldName2, strTableName);

filerering / replacing single quote in java

How do I filter single quotes ' in java?
I have a search box where if anyone types a single quote, I get a database error.
I don't want to filet it in JavaScript or at Database level; I want to do it in Java only. How can I do that?
I don't want to lose it completely. Is there any other way? Will replacing the quote with \' work??
I think you're approaching the problem from the wrong angle. I strongly suspect you're building your SQL like this:
String sql = "SELECT * FROM TABLE WHERE USERID='" + userInput + "'";
or something similar. Don't do that. Use a parameterized query instead, and supply the user input as the parameter. Every database I've ever used knows how to handle that, and it's the safe way to handle user input.
If you really, really just want to get rid of quotes, you can use:
text = text.replace("'", "");
... but please don't. Use a parameterized query instead.
Yes, use PreparedStatement.setString():
String sql = "SELECT * FROM table WHERE USERID = ?";
PreparedStatement pstmt = connection.prepareStatement(sql);
pstmt.setString(1, "O'Connor");
ResultSet rs = pstmt.executeQuery();
Escaping rules for databases differ. For example in Oracle you can duplicate the apostrope to get it escaped. In MySQL it is backslash + apostrophe (I think).
So either userInput = userInput.replaceAll("'", "''"); or userInput = userInput.replaceAll("'", "\\'");

Categories