Search a ResultSet for a specific value method? - java

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.

Related

Getting Incorrect return in java accessing sql database

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();

Difference between CreateStatement and PreparedStatement in JDBC [duplicate]

This question already has answers here:
Difference between Statement and PreparedStatement
(15 answers)
Closed 9 years ago.
Hi I am trying to learn JDBC.
and here is my question:-
What is the Use of PreparedStatement in JDBC Because We can achieve the same effect by using createStatement(); too.
I mean if there is a query like:
Select * from tbl_name where id = somevalue
Then We can achieve it by both PreparedStatement and createStatement(). As follows:
Using CreateStatement():
try {
DataInputStream dis=new DataInputStream(System.in);
System.out.println("Enter id :- ");
int id=Integer.parseInt(dis.readLine());
String q="Select * from tbl_name where id="+id;
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(q);
while(rs.next()) {
//fetching part
}
} catch(Exception ex){ ... }
Using PreparedStatement:
try {
PreparedStatement preStatement=conn.prepareStatement("Select * from tbl_name where id=?");
DataInputStream dis=new DataInputStream(System.in);
System.out.println("Enter id:- ");
int id=Integer.parseInt(dis.readLine());
preStatement.setInt(1, id);
ResultSet result = preStatement.executeQuery();
while(result.next()){
// fetch the data
}
}catch(Exception ex){ ... }
As both of these programs are capable of doing the same task.
Why there is provision of two different Methods? Also looping seems to be easy if avoid repeatation is the answer.
Can any one tell me which one is good to use ?
what is the provision of each of them?
What is the difference between them, and which one optimizes the code?
The prepared statement concept is not specific to Java, it is a database concept. Precompiling of statement means, when you execute a SQL query, database server will prepare a execution plan before executing the actual query, this execution plan will be cached at database server for further execution.
The advantages of Prepared Statements are:
As the execution plan get cached, performance will be better.
It is a good way to code against SQL Injection as escapes the input values.
When it comes to a Statement with no unbound variables, the database is free to optimize to its full extent. The individual query will be faster, but the down side is that you need to do the database compilation all the time, and this is worse than the benefit of the faster query.
With the createStatement the underlying database has to parse and compile the passed select query every time the statement is executed. This can impact performance. You can kind of "save" the query logic in a prepared statement and just pass in the query parameters, which could be the variable part of your query, every time the statement is executed.

No return data from PreparedStatement query

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.

Create method which returns resultset from sql query

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

How can I get previous item in resultset?

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.

Categories