My query is throwing up this error while i have column Accessoires in table categorie Can anyone see why?
public int rechercheParCat(String test) {
int idcat = 0;
try {
String query = "SELECT id_cat FROM categorie WHERE titre="+test;
PreparedStatement pst = cnx2.prepareStatement(query);
ResultSet rs = pst.executeQuery(query);
idcat = rs.getInt(1);
} catch (SQLException ex) {
System.err.println(ex.getMessage());
}
return idcat;
}
I FIXED IT LIKE THIS:
int idcat = 0;
try {
String query = "SELECT id_cat FROM categorie WHERE titre=? ";
PreparedStatement pst = cnx2.prepareStatement(query);
pst.setString(1, test);
ResultSet rs = pst.executeQuery();
rs.first();
idcat = rs.getInt(1);
} catch (SQLException ex) {
System.err.println(ex.getMessage());
}
return idcat;
}```
Using bound parameters with a prepared statement likely fixes your bug and also solves the severe security issue.
public int rechercheParCat(String test) {
int idcat = 0;
try {
String query = "SELECT id_cat FROM categorie WHERE titre = ?";
PreparedStatement pst = cnx2.prepareStatement(query);
pst.setString(1, test);
ResultSet rs = pst.executeQuery(query);
idcat = rs.getInt(1);
} catch (SQLException ex) {
System.err.println(ex.getMessage());
}
return idcat;
}
The likely reason your code has failed is that test was "Accessoires", so the resulting SQL statement was:
SELECT id_cat FROM categorie WHERE titre=Accessoires
when in fact it should have been:
SELECT id_cat FROM categorie WHERE titre='Accessoires'
Even if you added quotes to the concatenated statement, you'd still have a problem. Just imagine what happens if somebody passes a value with quotes, e.g. O'Connor. This will just break the code. But a more clever person can inject SQL clauses.
Related
Two tables are present in the database, one is Student table with columns roll_no(PK), name, grade and DOB, another table StudentLeft with columns roll_no, name, grade and leaving_date.
I want to delete the record of the student from Student table whose roll no is entered by the user, and add the roll no, name, grade and leaving_date (the date when the record is deleted and added to the table) to StudentLeft table.
This is my method.
public static void main(String[] args) throws SQLException {
Connection connection = null;
PreparedStatement preparedStatement = null, preparedStatement1 = null, preparedStatement2 = null;
ResultSet resultSet = null;
String selectQuery = "", updateQuery = "", deleteQuery = "";
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
connection = dataSource.getConnection();
}
catch (ClassNotFoundException e) {
e.printStackTrace();
}
catch (SQLException e) {
e.printStackTrace();
}
int rollNo = Integer.parseInt(args[0]);
try {
selectQuery = "SELECT name, grade FROM Student WHERE roll_no = ?";
updateQuery = "INSERT INTO StudentLog values WHERE roll_no = ?, name = ?, standard = ?";
deleteQuery = "DELETE Student WHERE roll_no = ?";
connection.setAutoCommit(false);
preparedStatement = connection.prepareStatement(selectQuery);
preparedStatement.setInt(1, rollNo);
resultSet = preparedStatement.executeQuery();
preparedStatement1 = connection.prepareStatement(updateQuery);
preparedStatement1.setInt(1, rollNo);
while (resultSet.next()) {
String name = resultSet.getString("name");
String grade = resultSet.getString("grade");
preparedStatement1.setString(2, name);
preparedStatement1.setString(3, grade);
preparedStatement1.addBatch();
}
preparedStatement1.executeBatch();
preparedStatement2 = connection.prepareStatement(deleteQuery);
preparedStatement.setInt(1, rollNo);
connection.commit();
}
catch (SQLException e) {
e.printStackTrace();
}
try {
if (!preparedStatement.isClosed() || !preparedStatement1.isClosed() || !preparedStatement2.isClosed()) {
preparedStatement.close();
preparedStatement1.close();
preparedStatement2.close();
}
if (!connection.isClosed())
connection.close();
}
catch (SQLException e) {
e.printStackTrace();
}
}
These are the errors.
java.sql.BatchUpdateException: ORA-00936: missing expression
at oracle.jdbc.driver.OraclePreparedStatement.executeBatch(OraclePreparedStatement.java:10500)
at oracle.jdbc.driver.OracleStatementWrapper.executeBatch(OracleStatementWrapper.java:230)
at Q3.main(Q3.java:48)
Exception in thread "main" java.lang.NullPointerException
at Q3.main(Q3.java:62)
I am using oracle 11g express database.
The code you've written can be simplified quite a bit:
public static void main(String[] args) {
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
}
catch (ClassNotFoundException e) {
e.printStackTrace();
return;
}
int rollNo = Integer.parseInt(args[0]);
try (Connection connection = dataSource.getConnection()) {
connection.setAutoCommit(false);
String transferStatement = "INSERT INTO StudentLog (roll_no, name, standard, leaving_date) " +
"SELECT roll_no, name, standard, SYSDATE FROM Student WHERE roll_no = ?";
try (PreparedStatement stmt = connection.prepareStatement(transferStatement)) {
stmt.setInt(1, rollNo);
stmt.executeUpdate();
}
String deleteStatement = "DELETE FROM Student WHERE roll_no = ?";
try (PreparedStatement stmt = connection.prepareStatement(deleteStatement)) {
stmt.setInt(1, rollNo);
stmt.executeUpdate();
}
connection.commit();
}
catch (SQLException e) {
e.printStackTrace();
}
}
I've used try-with-resources statements, which simplifies the clean-up of connections and prepared statements: the connection and statements will get closed when the code inside the try (...) block finishes executing.
Transferring data from the Student table to the StudentLog table can be done in one go with an INSERT INTO ... SELECT statement. This statement doesn't return any result set: there's nothing to iterate through, we just execute it and the row gets inserted.
The DELETE statement is similar: it too returns no result set. I've added the keyword FROM to it out of convention more than anything else: as pointed out on another answer, FROM is optional.
I've also moved the catch (SQLException e) block to the end: that will handle all SQLExceptions generated when connecting to the database or executing either of the prepared statements.
I've kept the code that attempts to load the Oracle database driver class, but added a return statement in the catch block: if there's an exception, the driver isn't on the classpath and connecting to the database is guaranteed to fail so we may as well stop. However, for recent versions of the Oracle driver you don't need this check. Experiment with it: see if the code works without this check and if so, remove it.
Shouldn't your query be
DELETE FROM Student WHERE roll_no = ?
instead of
DELETE Student WHERE roll_no = ?
Your DELETE code used the wrong prepared statement, missing an execute.
It is advisable to use try-with-resources as below, for the automatic closing,
even on return or exception. (It also takes care of variable scopes.)
public static void main(String[] args) throws SQLException {
int rollNo = Integer.parseInt(args[0]);
// Better statements possible.
final String selectQuery = "SELECT name, grade FROM Student WHERE roll_no = ?";
final String updateQuery =
"INSERT INTO StudentLog VALUES WHERE roll_no = ?, name = ?, standard = ?";
final String deleteQuery = "DELETE FROM Student WHERE roll_no = ?";
try { // Check whether you need this. It is for the old discovery mechanism.
Class.forName("oracle.jdbc.driver.OracleDriver");
}
catch (ClassNotFoundException e) {
throw new IllegalStateException("Database driver not provided", e);
}
try (Connection connection = dataSource.getConnection()) {
connection.setAutoCommit(false);
try (PreparedStatement preparedStatement =
connection.prepareStatement(selectQuery)) {
preparedStatement.setInt(1, rollNo);
try (ResultSet resultSet = preparedStatement.executeQuery()) {
try (PreparedStatement preparedStatement1 =
connection.prepareStatement(updateQuery)) {
preparedStatement1.setInt(1, rollNo);
while (resultSet.next()) {
String name = resultSet.getString("name");
String grade = resultSet.getString("grade");
preparedStatement1.setString(2, name);
preparedStatement1.setString(3, grade);
preparedStatement1.addBatch();
}
preparedStatement1.executeBatch();
}
}
}
try (PreparedStatement preparedStatement2 =
connection.prepareStatement(deleteQuery)) {
preparedStatement2.setInt(1, rollNo); // NOT preparedStatement
preparedStatement2.executeUpdate();
}
connection.commit();
}
}
Then one should SELECT+INSERT to the database, using one statement (INSERT SELECT).
The SQL of the StudentLog is a bit incomprehensible to me, but a nice INSERT would be:
INSERT INTO StudentLog VALUES(roll_no, name, standard)
SELECT roll_no, name, grade
FROM Student
WHERE roll_no = ?
Removing the need java nesting of database accesses.
I have written a simple method to get a string out of the database:
public String getUserString(int id, String table, String column) {
String output = null;
try {
String sql = "SELECT ? FROM ? WHERE id=?;";
PreparedStatement preparedStatement = getConnection().prepareStatement(sql);
preparedStatement.setString(1, column);
preparedStatement.setString(2, table);
preparedStatement.setInt(3, id);
ResultSet resultSet = preparedStatement.executeQuery();
while (resultSet.next()) {
output = resultSet.getString(column);
}
} catch (SQLException e) {
e.printStackTrace();
}
return output;
}
But when I try to use it like this: coreMySQL.getUserString(1, "economy", "balance");
I get this error:
https://pastebin.com/BMAmN4Xh
You can't set table name and column names with setXxx method(s) for PreparedStatement. It can only be used to set the values.
However, you can do a simple String replace to substitute table names and column names, e.g.:
String query = SELECT <column> FROM <table> WHERE id=?;
String sql = query.replaceAll("<column>", column).replaceAll("<table>", table);
PreparedStatement preparedStatement = getConnection().prepareStatement(sql);
preparedStatement.setInt(1, id);
ResultSet resultSet = preparedStatement.executeQuery();
while (resultSet.next()) {
output = resultSet.getString(column);
}
Define a query template as:
String queryTemplate = "SELECT %s FROM %s where id = ?;";
// Inside Function:
PreparedStatement preparedStatement = getConnection().prepareStatement(String.format(template, column, table));
preparedStatement.setInt(1, id);
ResultSet resultSet = preparedStatement.executeQuery();
I wrote some java code to display database, when I run the code it gives me just the last element of database , but I wanna display all elements of table
the code :
public String RecupererPuissance() {
try {
Connection con = myDbvoiture.getConnection();
String queryPattern ="select Power from bd_voiture";
PreparedStatement pstmt = con.prepareStatement(queryPattern);
ResultSet rs = pstmt.executeQuery();
while (rs.next()) {
puissance=rs.getString("Power");
System.out.println(puissance);
}
} catch (SQLException ex) {
System.err.println(ex.getMessage());
}
return puissance;
}
What should I do? Can anyone please help me to display all values?
Thank you for helping me.
I think the problem is with your code that the value of puissance is overwritten every time you get the next element. Only the last value is returned. You should put the results into a list and return the whole list:
public List<String> RecupererPuissance() {
List<String> puissances = new ArrayList<String>();
try {
Connection con = myDbvoiture.getConnection();
String queryPattern ="select Power from bd_voiture";
PreparedStatement pstmt = con.prepareStatement(queryPattern);
ResultSet rs = pstmt.executeQuery();
while (rs.next()) {
puissance = rs.getString("Power");
puissances.add(puissance);
System.out.println(puissance);
}
} catch (SQLException ex) {
System.err.println(ex.getMessage());
}
return puissances;
}
public String RecupererPuissance() {
try {
Connection con = myDbvoiture.getConnection();
String queryPattern ="select Power from bd_voiture";
PreparedStatement pstmt = con.prepareStatement(queryPattern);
ResultSet rs = pstmt.executeQuery();
rs.first();
int count=0;
while (rs.next()) {
System.out.println("count = "+count);
count+=1;
puissance=rs.getString("Power");
System.out.println(puissance);
}
} catch (SQLException ex) {
System.err.println(ex.getMessage());
}
return puissance;
}
If you see count printed only 1 time :
it would mean that you have only 1 row in column Power
and you maybe referring to the wrong column in your code
I want to use two sql query in my java code. the first query retain all row of table2 and the second one get it's rows one by one. I wrote follow code but it face to "This ResultSet is closed, it means rs ResultSet " error. How can I fix?
try{
String sqlSelectTable2 = "SELECT * FROM table2;";
ResultSet rs = stmt.executeQuery(sqlSelectTable2);
while (rs.next()) {
String strLineId = rs.getString(1);
String strPoints = rs.getString(2);
String sqlWithin = "SELECT ST_Within(ST_GeometryFromText('POINT( ),ST_GeomFromText('POLYGON((443425 4427680, 441353 4427680, 441368 4426075, 443762 4426149, 443425 4427680))', 4326));";
ResultSet rsWithin = stmt.executeQuery(sqlWithin);
} // end while ... **It get error when it is reading second ResultSet **
} catch (Exception e) {
System.out.println(e.getMessage());
}
You need to create separate PreparedStatement object for inner query
try{
String sqlSelectTable2 = "SELECT * FROM table2;";
ResultSet rs = stmt.executeQuery(sqlSelectTable2);
while (rs.next()) {
String strLineId = rs.getString(1);
String strPoints = rs.getString(2);
PreparedStatement preparedStatement = null;
String sqlWithin = "SELECT ST_Within(ST_GeometryFromText('POINT( ),ST_GeomFromText('POLYGON((443425 4427680, 441353 4427680, 441368 4426075, 443762 4426149, 443425 4427680))', 4326));";
preparedStatement = dbConnection.prepareStatement(sqlWithin);
ResultSet rsWithin = preparedStatement.executeQuery();
} // end while ... **It get error when it is reading second ResultSet **
} catch (Exception e) {
System.out.println(e.getMessage());
}
In my database bean I have a section of code which is below :
public Integer getTotalOrgPoints() {
try {
PreparedStatement stmt = ConnectionHandler.getConnection().prepareStatement(QUERY_TOTAL_ORG_SCORE);
ResultSet rs = stmt.executeQuery();
while (rs.next()) {
totalOrgPoints = rs.getInt(1);
}
} catch (SQLException e) {
System.out.println(e.getMessage());
}
return totalOrgPoints;
}
For the statement QUERY_TOTAL_ORG_SCORE if I use
SELECT SUM(users.score)
FROM user_organisation_relationships
INNER JOIN users
ON user_organisation_relationships.user_id = users.id
WHERE organisation_id = 1
It will return the value for that organisation but if I use
SELECT SUM(users.score)
FROM user_organisation_relationships
INNER JOIN users
ON user_organisation_relationships.user_id = users.id
WHERE organisation_id = ?
I get nothing does anyone know why this is happening for me?.
Add this line to bind values for prepared statement before executequery
stmt.setInt(1, 1);
Modified:-
PreparedStatement stmt = ConnectionHandler.getConnection().prepareStatement(QUERY_TOTAL_ORG_SCORE);
stmt.setInt(1, 1);
ResultSet rs = stmt.executeQuery();