This question already has answers here:
Variable column names using prepared statements
(7 answers)
Closed 4 years ago.
In a university task I'm using JDBC to access a database. I wrote a finder-method that could find objects in a table by any value in any column that has integer values.
public ResultSet findSampleByAnyCol(String colName, Integer sampleId, Connection con) {
ResultSet rs = null;
String sql = "SELECT * FROM sample WHERE ? = ?";
try(PreparedStatement pstmt = con.prepareStatement(sql)) {
pstmt.setString(1, colName);
pstmt.setInt(2, sampleId);
rs = pstmt.executeQuery();
}catch(SQLException e) {
e.printStackTrace();
}
return rs;
}
I tested it and I'm sure the problem is that "?" for the colum nname doesn't work. The stack trace says "invalid number". But if I change the SQL statement to SELECT * FROM sample WHERE sampleid = ? it works fine.
Just found the answer here, it´s not possible to do that. The "?" is just for values. To have variable columnnames it´s inevitable to do it with an own string manipulation.
Related
This question already has an answer here:
ResultSet is not for INSERT query? Error message: Type mismatch: cannot convert from int to String
(1 answer)
Closed 5 years ago.
I am getting a error on the resultset rs part where netbeans shows the error as
incompatible types:int cannot be converted to resultset
Class.forName("java.sql.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mysql?useSSL=false", "root", "abc");
Statement stmt = conn.createStatement();
String query = "SELECT * FROM patient WHERE Mobile_No='" + mobno + "';"; /*Get the value from the database*/
ResultSet rs = stmt.executeUpdate(query);/*Part where the error is appearing*/
while (rs.next()) {
String Name = rs.getString("Name");
String Age = rs.getString("Age");
String Mobile = rs.getString("Mobile_No");
String gender = rs.getString("Gender");
String symptoms = rs.getString("Symptoms");
model.addRow(new Object[]{Name, Age, Mobile, gender, symptoms});
}
rs.close();
stmt.close();
conn.close();
Use stmt.executeQuery(String sql), it returns ResultSet.
If you want a ResultSet returned you should use executeQuery, not executeUpdate.
The stmt.executeUpdate(query); doesn't fit for an SELECT query.
You need to replace it by stmt.executeQuery(query);
Well the method executeUpdate returns a int not a results set, seen in the documentation here: https://docs.oracle.com/javase/7/docs/api/java/sql/Statement.html#executeUpdate(java.lang.String)
the integer being return being either (1) the row count for SQL Data Manipulation Language (DML) statements or (2) 0 for SQL statements that return nothing
the method you are actually want to use is executeQuery and the documentation for that can be found at:
https://docs.oracle.com/javase/7/docs/api/java/sql/Statement.html#executeQuery(java.lang.String)
According the Javadoc (https://docs.oracle.com/javase/9/docs/api/java/sql/Statement.html#executeUpdate-java.lang.String-), stmt.executeUpdate(query); returns an int and not a ResultSet object.
From the Javadoc :
Returns:
either (1) the row count for SQL Data Manipulation Language (DML) statements or (2) 0 for SQL statements that return nothing
I think you must use stmt.executeQuery(query); instead, which return the ResultSet you expect. You're doing a SELECT and not an INSERT, UPDATE, or DELETE operation.
I believe people have already answered your question, which is statement.executeUpdate(query) returns the number of how many rows has been affected by executing the query, and you should use statement.executeQuery(query) instead ..
But this part String query = "SELECT * FROM patient WHERE Mobile_No = '" + mobno + "';" is very bad approach, it will leave the door opened for SQL injection, you should use PreparedStatement instead of Statement
This question already has answers here:
Getting java.sql.SQLException: Operation not allowed after ResultSet closed
(2 answers)
Closed 4 years ago.
Can anyone point me in the write direction to solve the error: SQLException: Operation not allowed after ResultSet closed
Here is the code i believe the error occurs in
Statement stmt = con.createStatement();
String query1 = "";
String query2 = "";
int candidateNo = 42;
query1 = "SELECT * FROM Candidates WHERE CandidateNo = "+ candidateNo;
ResultSet rs = stmt.executeQuery(query1);
//If query can be completed then display name and prompt to continue
if(rs.next()){
query2 = "SELECT * FROM Achieved WHERE CandidateNo = " + candidateNo;
ResultSet ts = stmt.executeQuery(query2);
}
I have tried using resultset rs = null; to create the variable but the error still occurs
You are iterating over the ResultSet bound to a Statement , then while iterating, you are using the exact same Statement object to issue a new query and get and iterate over another ResultSet .
This won't work as long as you are not done with the processing of the first ResultSet, so consider using a distinct Statement object for your second query .
In your code you used 2 ResultSet executing the same Statement object (stmt)concurrently. Use different Statement Objects for both queries.
This question already has answers here:
Using Prepared Statements to set Table Name
(8 answers)
Closed 6 years ago.
I just learned about prepared statements and now I'm trying to include them to my java program. However I get an exception when I try to add to values to the statement( table and name). When I prepare with only one variable it works fine.
What am I doing wrong?
[SQLITE_ERROR] SQL error or missing database (near "?": syntax error)
String sql="SELECT * FROM ? WHERE name = ?";
try {
PreparedStatement preparedStatement = connection.prepareStatement(sql);
preparedStatement.setString(1, table);
preparedStatement.setString(2, name);
ResultSet checkTable = preparedStatement.executeQuery();
That's not how prepared statements work. Oddly enough, you can't use placeholders for table names. The solution being to use something like:
String sql = String.format("SELECT * FROM %s WHERE name = ?", table);
... and proceed with the rest of your code.
Prepared statement are for values, a table name is not considered as being a value. So what you try to achieve is not possible.
That would work, though :
String sql="SELECT * FROM any_table_name WHERE name = ?";
try {
PreparedStatement preparedStatement = connection.prepareStatement(sql);
preparedStatement.setString(1, name);
ResultSet checkTable = preparedStatement.executeQuery();
} catch (Exception e) {}
Prepared statements are for column values not table names. You should do it as follows.
String sql = "SELECT * FROM `" + table + "` WHERE name = ?";
This question already has answers here:
Using Prepared Statements to set Table Name
(8 answers)
Closed 7 years ago.
Is there a limit to PreparedStatement variables (?) or requirements for their placement?
I have a method that takes in the parameters to complete a PreparedStatement however, it throws a SQLException.
Here is the PreparedStatement I want to use:
String update = "UPDATE ? SET ? = ? WHERE UserID = ?";
When I add in the first and second variables it runs just fine. Here is the working PreparedStatement:
String update = "UPDATE Student SET First_Name = ? WHERE UserID = ?";
Is there a reason I cannot get the first statement to work?
The entire method:
public static void runUpdate(String givenID, String givenAttribute, String givenUpdate) throws SQLException
{
// Establish the connection with the database
Connection conn = SimpleDataSource.getConnection();
try
{
// Create a string with the SQL Update statement
String update = "UPDATE ? SET ? = ? WHERE UserID = ?";
// Make a Prepared Statement with the connection to the database
PreparedStatement stat = conn.prepareStatement(update);
try
{
// Set the statement with the given parameters
stat.setString(1, Utility.getType(givenID));
stat.setString(2, givenAttribute);
stat.setString(2, givenUpdate);
stat.setString(3, givenID);
// Execute the Update Statement
stat.executeUpdate();
}
finally
{
// Close the prepared Statement
stat.close();
}
}
finally
{
// Close the connection to the database
conn.close();
}
}
You can't use the query like this.
String update = "UPDATE ? SET ? = ? WHERE UserID = ?";
You should write the name of table and the name of the column like here.
String update = "UPDATE table SET column_name = ? WHERE UserID = ?";
You can use variables in prepared statements only as placeholder of literals in SQL statements. So you cannot use them for column name, or table names. For these you should resort to dynamic SQL statements.
This question already has answers here:
How do I get the size of a java.sql.ResultSet?
(15 answers)
Closed 8 years ago.
I need your assistant and help in getting the count of the values which are available in the resultset. The resultset is having 22 records and in the below code, it is printing the count starting from 1 to 23. Is there any way to get the total no. of records as 22 (one value only) or by subtracting the last value from the first value?
My code is below:
while (rs.next())
{
count=0;
name1=rs.getString("name");
out.println(rs.getRow());
}
I tried to use rs.first() and rs.last() and it produced the below error:
java.sql.SQLException: Invalid operation for forward only resultset :
first
I tried to add the arguments to the createstatement, but the same exception is there:
conn.createStatement(rs.TYPE_SCROLL_INSENSITIVE, rs.CONCUR_READ_ONLY);
java.sql.SQLException: Invalid operation for forward only resultset :
last
Please help me in the above issue.
Try this:
int rowcount = 0;
if (rs.last()) {
rowcount = rs.getRow();
rs.beforeFirst();
}
EDIT:
You need to change the statement of your query like this so that you can use the rs.last()
Statement stmt = con.createStatement(rs.TYPE_SCROLL_INSENSITIVE);
ResultSet rs = stmt.executeQuery("Your query");
Check Oracle Docs
You can use MySQL's count(*)
try{
Statement stmt = connection.createStatement();
String selectquery = "select count(*) from YourTable";
ResultSet rs = stmt.executeQuery(selectquery);
rs.next();
System.out.println("Amount of rows :" + rs.getInt(1));
}
If you wanna count rows based on "name", then
try{
Statement stmt = connection.createStatement();
String selectquery = "select count(name) from YourTable";
ResultSet rs = stmt.executeQuery(selectquery);
rs.next();
System.out.println("Amount of rows :" + rs.getInt(1));
}