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));
}
Related
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.
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 an answer here:
Passing an Array to a SQL query using Java's PreparedStatement
(1 answer)
Closed 7 years ago.
I am using mySQL JDBC driver in my java program. I want to pass a ArrayList in the IN clause in my SQL query.
i did use a prepared statement like this, but this throws an
"java.sql.SQLFeatureNotSupportedException"exception
since mysql doesn't support this.
ArrayList<String> list = new ArrayList<String>();
PreparedStatement pstmt =
conn.prepareStatement("select * from employee where id in (?)");
Array array = conn.createArrayOf("VARCHAR", list.toArray());
pstmt.setArray(1, array);
ResultSet rs = pstmt.executeQuery();
Is there any other way to do this ? Maybe with Statement stmt.
Build the SQL statement with the correct number of markers, and set all the values.
Beware: Databases have a limit to the number of parameters allowed, though it's very high for MySQL (65535).
char[] markers = new char[list.size() * 2 - 1];
for (int i = 0; i < markers.length; i++)
markers[i] = (i & 1 == 0 ? '?' : ',');
String sql = "select * from employee where id in (" + markers + ")";
try (PreparedStatement stmt = conn.prepareStatement(sql)) {
int idx = 1;
for (String value : list)
stmt.setString(idx++, value);
try (ResultSet rs = stmt.executeQuery()) {
while (rs.next()) {
// code here
}
}
}
How to get the outcome of the query-- the AVG(DIST).
MySQL is showing this result under the column "AVG(DIST)"-- no other clue.
How do i read this value from the ResultSet instance (rs in below code)?
PreparedStatement ps = c.prepareStatement("SELECT AVG(DIST) FROM POOL_TABLE");
ResultSet rs = ps.executeQuery();
ResultSet seems to be referring to them all by column names.
Not well-familiar to JDBC -- yet!
TIA.
You can use an alias name in the query and retrieve the value in any of the two ways.!
PreparedStatement ps = c.prepareStatement("SELECT AVG(DIST) AS AVERAGE_ALIAS FROM POOL_TABLE");
ResultSet rs = ps.executeQuery();
double avg = 0;
while (rs.next()) {
avg = rs.getDouble(1);
// OR
avg= rs.getDouble("AVERAGE_ALIAS");
}
Here it is:
double avg = 0;
while (rs.next()) {
avg = rs.getDouble(1);
}
Use alias if you have many aggregate functions in your query. See below answer!
PreparedStatement used for inserting of data,
i think you should use Statement.
Statement stmt = c.createStatement();
ResultSet rs = stmt.executeQuery("SELECT AVG(DIST) FROM POOL_TABLE");
if( rs.next() ){
System.out.print( rs.getString(1) );
}
i hope this example would help you :)