Suppose we have this query:
ResultSet result = ("select * from table_name");
Now we can get information from result in this form
while(result.next())
{
.
.
.
}
but in this form we can go forward. Now I want to know if it possible that result get back?
For example we get information name='sam', fname='nic'. And for next I want go back and get this information again.
Is it possible?
Yes, JDBC supports that. You need to a scrollable resultset.
Something like this:
Statement st = conn.createStatement(
ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY
);
ResultSet rs = st.executeQuery("select * from table_name");
Then you just use ResultSet object rs to move within your results:
first
absolute
last
next
previous
Are methods that will help you navigate.
When you create a Statement without passing parameters to it, it defaults to ResultSet.TYPE_FORWARD_ONLY.
Statement st = con.createStatement();
If you want to be able to scroll back you set the first parameter to either ResultSet.TYPE_SCROLL_INSENSITIVE or ResultSet.TYPE_SCROLL_SENSITIVE. (Insensitive or sensitive in regard to changes to the database by others.)
Statement st = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
CONCUR_UPDATABLE will allow you to update the ResultSet if you want, unless you do not need to, i which case you set it to CONCUR_READ_ONLY.
Read this.
Related
I am creating a new register in table MY_TABLE using java and then, I am doing a query to obtain the max(id) of that table. However, Java is obtaining the previous one. I mean:
mybean.store(con)
con.commit();
pstm = con.prepareStatement("SELECT MAX (ID) FROM MY_TABLE");
rs = pstm.executeQuery();
while (rs.next()){
id = rs.getString("ID");
System.out.println("id: " +id);
}
Before con.commit(); the table has the max(ID)=3
After com.commit() the table has the max(ID)=4
But I obtain MAX(ID)=3
Can somebody help me to solve this?
You're doing it; if this is returning the wrong result either your DB doesn't contain what you think it contains, or your DB engine is broken (MySQL is often broken, possibly that's the problem. The fix is to not use mysql), or your code is broken. Your snippet contains an error (no semicolon after the first line), so this isn't a straight paste but a modification; generally you should paste precisely the code that is exhibiting the behaviour you don't understand, because if you edit it or try to simplify it without running the simplification, you may have accidentally removed the very thing that would explain what you're observing.
More generally, if all you want is the ID generated for an auto-increment column, this isn't how you do it. You can use statement's .getGeneratedKeys() method to get at these; you may have to pass in Statement.RETURN_GENERATED_KEYS as part of your executeUpdate call.
You do not need a PreparedStatement if you do not have a parametrized query. I would use Statement in this case.
You do not need while (rs.next()) as your query will return a single value. I would use if (rs.next()).
Your query does not have a field called ID and therefore rs.getString("ID") will throw SQLException. You should use rs.getString(1) or use an alias (e.g. maxId in the example shown below) in the query. Also, you should use getInt instead of getString.
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("SELECT MAX(ID) AS maxId FROM MY_TABLE");
int id = Integer.MIN_VALUE;
if (rs.next()) {
id = rs.getInt(1);
//id = rs.getInt("maxId");
}
System.out.println(id);
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 do a SELECT using PreparedStatement, but not getting any results back, despite the data being present. If I use Statement instead, I get the desired results, so not sure why I don't get anything with the PreparedStatement.
Any ideas?
Here is my code:
String species = "Snail";
PreparedStatement preparedStatement = con.prepareStatement("Select * from lifeforms where species=?",PreparedStatement.RETURN_GENERATED_KEYS);
preparedStatement.setString(1, species);
preparedStatement.execute();
ResultSet resultSet = preparedStatement.getGeneratedKeys();
Also - I have tried just
resultSet = preparedStatement.execute();
But this won't compile, saying I must change resultSet to expect a boolean value.
Any insights into this would be greatly appreciated.
Sorry if this is something obvious, but I have read the docs until I am almost unconscious, and I'm only just learning java.
The execute() functon returns a boolean value so u won't be able to put this in an object of resultset, if you want to execute a select statement you have to use executeQuery().
Ah so I have finally found the answer to this question - in case anyone else is stuck on the same thing..
The execute() method has no return value, although the compiler was suggesting it expected a boolean return value. Maybe it just returns true or false for successful or not?
The executeUpdate() method returns an int value of the number of records updated/inserted or deleted.
To get the result set of a query statement (e.g. Select * from someTable), use the
ResultSet rs = preparedStatement.executeQuery() method.
This will return the actual query results into a ResultSet variable.
I have a little problem with creating a method which takes String as parameter and return ResultSet after execute the query.Here is an example actually what I'm trying to do :
public ResultSet executeSQLQuery(String query){
ResultSet rs = sqliteDb.rawQuery(query,null);;
return rs;
}
Something like this, but it says that I have to convert rs to cursor type, but I need to return RS. Any ideas how to get the things to work?
possible duplicate
The result set isn't available, at least for now, in sqlite. It all depends on exactly what information you want from the ResultSet or ResultSetMetaData, etc, but there are other means of obtaining almost the same information.
check this link
to get resultset from pre-complie statement in android
Is there a ResultSet method that I can use that would search through a ResultSet and check whether it has the specific value/element?
Similar to ArrayList.contains() method.
If there isn't, you don't need to type up a search method, I'll make one :)
Thanks in advance.
Don't do the search in Java side. That's unnecessarily slow and memory hogging. You're basically taking over the job the DB is designed for. Just let the DB do the job it is designed for: selecting and returning exactly the data you want with help of the SQL language powers.
Start learning the SQL WHERE clause. For example, to check if an username/password mathes, do:
connection = database.getConnection();
preparedStatement = connection.prepareStatement("SELECT * FROM user WHERE username=? AND password=md5(?)");
preparedStatement.setString(1, username);
preparedStatement.setString(2, password);
resultSet = preparedStatement.executeQuery();
if (resultSet.next()) {
// Match found!
} else {
// No match!
}
Assuming you mean a SQL ResultSet, the answer is no, you have to write one. The JDBC driver usually won't retrieve all the rows at once (what if the query returned 1 million rows). You will have to read the rows and filter them yourself.