I'm tring to write a query but I obtain a syntax error. I know that this error is in the query's syntax. This is the query
ResultSet set=statement.executeQuery("Select * from Ombrellone where PosizioneX='"+c.getX()+"',PosizioneY='"+c.getY()+"'" );
Anyone can help me?
If you want to have multiple conditions on select, you must use AND, not comma.
ResultSet set=statement.executeQuery("Select * from Ombrellone where PosizioneX='"+c.getX()+"' and PosizioneY='"+c.getY()+"'" );
Side note : Avoid using String concatination with query parameters. They causes SQL injections and try using PreparedStatement.
Though the problem in your case was basically because you used comma on your SQL query which is wrong you can use AND or OR for condition fulfillment when using WHERE clause but also
I would suggest you to use PreparedStatement over Statement.
String query = "Select * from Ombrellone where PosizioneX = ? and PosizioneY = ?"
PreparedStatement statement = conn.prepareStatement(query);
statement.setString(1,c.getX());
statement.setString(2,c.getY());
ResultSet resultSet = statement.executeQuery();
Refer difference between statement and preparedstatement
Related
This is the code im using in java to query the database
connect = DriverManager.getConnection (url, "user", "pass");
state = connect.createStatement();
String meetID = "SELECT GamerTag FROM backup";
ResultSet rs = state.executeQuery(meetID);
while(rs.next()){
System.out.println(rs.toString());
}
Im not getting the values of the row in the database im getting this instead
com.mysql.jdbc.JDBC4ResultSet#108137c9
You're printing the result of the toString method of the Recordset object, which appears to print out the object's name and hashcode.
Instead, try to print the value of a column. Perhaps using getString:
System.out.println(rs.getString("GamerTag"));
The documentation for Java's recordset looks confusing, you might be better off searching for examples.
What do you expect rs.toString() should do it will just print the hash of the resultsetObject if you want to get the column values you should do this way
while(rs.next()){
System.out.println(rs.getString("yourFirstColumnName")+" "+
rs.getString("yourSecondColumnName")+" "+
rs.getString("yourThirdColumnName"));
}
Really you should use PreparedStatement. In your case though you are not using any parameterizedQuery but One of the major benefits of using PreparedStatement is better performance. PreparedStatement gets pre compiled.
In database and there access plan is also cached in database, which allows database to execute parametric query written using prepared statement much faster than normal query because it has less work to do. You should always try to use PreparedStatement.
So you can do something like this
String query = "SELECT GamerTag FROM backup"
PreparedStatement st =connect.prepareStatement("query");
ResultSet rs = st.executeQuery();
I am trying to write a very simply query using the PreparedStatement class. I read here:Fail to convert to internal representation JDBC that you cannot parameterize column names, only values. Since my query is very simple, the only 'value' I can parameterize is count (*).
This is the query:
SELECT COUNT (*) FROM EZ_DAY
If I try to parameterize it like this:
SELECT ? FROM EZ_DAY
I get an error:
Fail to convert to internal representation
when using the method getInt() on the ResultSet.
How can I use PreparedStatement and parameterize something in this query to prevent SQL injection? Also I know you can't parameterize column names, does that include table names? For example, can I do something like:
SELECT COUNT (*) FROM ?
?
That query cannot fall into SQL injection. The queries that fall in this category are those queries that you build by plain String concatenation. For example:
String query = "SELECT COUNT(*) FROM EZ_DAY WHERE colX = " + stringParameter;
Statement stmt = con.createStatement(query);
ResultSet rs = stmt.executeQuery();
In your case, there's no parameter to inject, so there's no way to have a SQL injection attack for your specific case.
If you need to prevent from SQL injection attacks, use PreparedStatement and do not concatenate the query. Instead, pass the parameters through the interface, which will escape any invalid character for you:
String query = "SELECT COUNT(*) FROM EZ_DAY WHERE colX = ?";
PreparedStatement pstmt = con.prepareStatement(query);
pstmt.setString(1, stringParameter);
ResultSet rs = pstmt.executeQuery();
In case you need to build a dynamic query, then you may fall back into concatenating strings, regardless if you use plain String concatenation or a StringBuilder:
//Common solution, still suffers from SQL injection
String query = "SELECT COUNT(*) FROM EZ_DAY WHERE 1 = 1 ";
if (stringParameter != null) {
query = query + = "AND colX = " + stringParameter;
}
Instead, it is better to use a COALESCE or IFNULL function to the parameter to avoid such situations:
//Better solution
String query = "SELECT COUNT(*) FROM EZ_DAY WHERE colx = COALESCE(?, colx)";
In the case above:
If the parameter has a different value than null, the query would be like this:
String query = "SELECT COUNT(*) FROM EZ_DAY WHERE colx = ?";
If the parameter has null value, then the query would be like this:
String query = "SELECT COUNT(*) FROM EZ_DAY WHERE colx = colx";
In the last example, you're still able to use PreparedStatement and avoid SQL injection attacks.
Related:
Difference between Statement and PreparedStatement
As explained in this post, SQL injection can lead to very serious issues like:
call a sleep function so that all your database connections will be busy, therefore making your application unavailable
extracting sensitive data from the DB
bypassing the user authentication
And it's not just SQL that can be affected. Even JPQL can be compromised if you are not using bind parameters.
Bottom line, you should never use string concatenation when building SQL statements. Use a dedicated API for that purpose:
JPA Criteria API
jOOQ
I am having some trouble with, what I believe to by syntax, for prepared statements.
I have the following code
String query2="SELECT lname FROM school_student WHERE sid = ? ORDER BY sid;";
PreparedStatement ps = cn.prepareStatement(query2);
ps.setInt(1, 3);
ResultSet rs = ps.executeQuery(query2);
The problem I am having is that I am getting this error message:
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '? ORDER BY sid' at line 1
However, when I substitute the "?" in my query for a 3, the query works fine with no error and gives me what I want. There seems to be something wrong with how I am setting the value of the "?" in my query? Am I using the wrong syntax?
Simply use
ps.executeQuery();
(i.e. use the overloaded executeQuery() method which doesn't take any argument). You already passed the query when preparing the statement.
use this query :-
String query2 = "SELECT lname FROM school_student WHERE sid =
"+attribute+" ORDER BY sid;";
and simply use
ps.executeQuery();
I think their is syntax problem while preparing query
try this one...
String query2="SELECT lname FROM school_student WHERE sid = +variablename+ ORDER BY sid;"
I'm having trouble with an SQL query. The problem is that I'm querying an external database of enterprise names and some names are like "Martha's" (include apostrophes). And because I'm querying from an android app, the query string looks like:
String query = "Select * from Advertiser where AdvName= '" + name + "';";
So is there anyway I could ignore or change the apostrophes in the query?
Thanks in advance!
That's one of the reasons why you should always use prepared statements when executing parameterized queries:
String sql = "select * from Advertiser where AdvName = ?";
PreparedStatement stmt = connection.prepareStatement(sql);
stmt.setString(1, name);
ResultSet rs = stmt.executeQuery();
The JDBC driver will escape the quotes for you, and this will also prevent SQL injection attacks.
Prepared statements also have performance advantages when you must execute the same query several times but with different parameters.
Read more about prepared statements in the JDBC tutorial.
Side note: you shouldn't have a ; at the end of your query.
In PLSQL you should use double '' in the input-field, meaning, Martha's => Martha''s:
String query = "Select * from Advertiser where AdvName= 'Martha''s';";
Important Remark:
For security purposes (to avoid sql injection) you should avoid creating queries the way you do, better use prepared-statement and set the parameters like this:
String query = "Select * from Advertiser where AdvName= ? ";
PreparedStatement st = conn.prepareStatement(query);
st.setString(1,name);
When I create a prepared statement like this in java (using JDBC):
pStmt = conn.prepareStatement(qry);
everything works ok. However when I want a scrollable resultset and use this:
pStmt = conn.prepareStatement(qry,ResultSet.TYPE_SCROLL_INSENSITIVE);
I get a syntax error:
org.postgresql.util.PSQLException: ERROR: syntax error at or near "RETURNING"
I'm not even using RETURNING in my query.
Any ideas?
Any help would be appreciated. Thanks
Update:
It seems to work if I use this:
pStmt = db.prepareStatement(qry,ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
What is the difference between SENSITIVE and INSENSITIVE?
Thanks
The second parameter to prepareStatement should be one of Statement.RETURN_GENERATED_KEYS or Statement.NO_GENERATED_KEYS.
I guess you want to use
PreparedStatement prepareStatement(String sql,
int resultSetType,
int resultSetConcurrency)
ResultSet.TYPE_SCROLL_INSENSITIVE : This assumes that the result set does not “sense” database changes that occurred after execution of the query.
ResultSet.TYPE_SCROLL_SENSITIVE : picks up changes in the database that occurred after execution of the query