Get specific row in ResultSet? - java

After getting results from a SQL query, I can access the results via a while loop :
String query = "SELECT TAX_RATE_ID FROM dbo.TAX_RATE where zip_code = 38401";
ResultSet rs= conn.createStatement().executeQuery(query);
while (rs.next()) {
System.out.println(rs.getString("TAX_RATE_ID"));
}
But I don't want to access them in a while loop, I want to just get the single result and return the value, since I know what to expect when the query is ran. So I tried this:
String query = "SELECT TAX_RATE_ID FROM dbo.TAX_RATE where zip_code = 38401";
ResultSet rs= conn.createStatement().executeQuery(query);
rs.first();
System.out.println(rs.getString("TAX_RATE_ID"));
But I get this error:
Exception in thread "main" java.sql.SQLException: ResultSet may only be accessed in a forward direction.
at net.sourceforge.jtds.jdbc.JtdsResultSet.checkScrollable(JtdsResultSet.java:319)
at net.sourceforge.jtds.jdbc.JtdsResultSet.first(JtdsResultSet.java:545)
at com.kirklands.automation.ecom.Testing.main(Testing.java:12)

You don't have to call next() in a loop. If you just want to get the first row, use:
String query = "SELECT TAX_RATE_ID FROM dbo.TAX_RATE where zip_code = 38401";
ResultSet rs= conn.createStatement().executeQuery(query);
if (rs.next()) {
System.out.println(rs.getString("TAX_RATE_ID"));
}
Unrelated, but:
conn.createStatement().executeQuery() will create a Statement instance that you can't clean up properly using close().

Related

Error "java.sql.SQLException: ORA-04054" JDBC-ORACLE

My code looks as follows:
ResulSet rs = stmt.executeQuery("select passwd from mrs_user where email="+mail_id);
String usr_paswd = rs.getString(1);
But the error is as follows:
java.sql.SQLException: ORA-04054: database link G.COM does not exist
mail_id=dk#g.com
First, String should be between to quotes 'mail_id', but this way is not secure it can cause SQL Injection or syntax error instead you can use PreparedStatement.
Second, you still not get any result, you have to call rs.next() before to moves the cursor to the next row (read about Retrieving and Modifying Values from Result Sets).
Code example
String usr_paswd = null;
try (PreparedStatement stmt = connection.prepareStatement(
"select passwd from mrs_user where email=?")) {
stmt.setString(1, mail_id);
ResulSet rs = stmt.executeQuery();
if(rs.next()){
usr_paswd = rs.getString(1);
}
}

Why does this Query return NULL?

I have a derby users database which I query, when the user clicks login on the application.
However, when I query the users table with the parameter [user] derby returns a null Object instead of the record it ought to return.
Here is my code:
String ssql = "SELECT * FROM USERS WHERE UNAME LIKE ?";
try{
DriverManager.registerDriver(new org.apache.derby.jdbc.EmbeddedDriver());
con = DriverManager.getConnection(url);
sql = con.prepareStatement(ssql, Statement.RETURN_GENERATED_KEYS);
sql.setString(1, cbox_chooseUser.getSelectedItem().toString());
sql.executeQuery();
ResultSet rs = sql.getGeneratedKeys();
try{
while (rs.next()) {
if(rs.getString("PW").toCharArray().equals(txt_password.getPassword())){
sql.close();
con.close();
return true;
}
} catch (NPE ...) {...}
}
I tried it multiple times wit a test user with both the pw and the username set to "test"; but I always get the same error.
Why is the recordset always Null?
Thanks for your help :)
The documentation says
ResultSet getGeneratedKeys() throws SQLException
Retrieves any auto-generated keys created as a result of executing this Statement
object.
If this Statement object did not generate any keys, an empty
ResultSet object is returned.
Your select statement isn't generating any keys that's why it's returning an empty ResultSet. You aren't inserting anything hence no keys are being generated.
You can try ResultSet rs = sql.executeQuery();. It should work.
You are using it in wrong way.
The generated keys concept should be used only in the case DML of insert type query but not in the case of select query.
select simply select the rows from the table. In this case there is no chance of any keys getting generated.
In the case of insert query if any column is configured as auto increment or kind of functionality then some keys will get generated. These keys can be caught using Statement.RETURN_GENERATED_KEYS in java.
As you are using select query there is no need of using Statement.RETURN_GENERATED_KEYS.
You just modify below lines and everything will be fine.
sql = con.prepareStatement(ssql, Statement.RETURN_GENERATED_KEYS);
sql.setString(1, cbox_chooseUser.getSelectedItem().toString());
sql.executeQuery();
ResultSet rs = sql.getGeneratedKeys();
with
sql = con.prepareStatement( ssql );
sql.setString( 1, cbox_chooseUser.getSelectedItem().toString() );
ResultSet rs = sql.executeQuery();

Retrieve Data from a SQL Query (SELECT FROM WHERE) in java

Well I was wondering if there is any other way to get data from a SQL Query.
What I mean is that the "main" code that I always find is
Connection con = (connect to db)
PreparedStatement st = con.prepareStatement(....);
ResultSet rs = ps.executeQuery();
while (rs.next())
{
//do something
}
But if I want to retrieve specific data for example lets assume that my query is
Connection con = L2DatabaseFactory.getInstance().getConnection();
PreparedStatement ps = con.prepareStatement("SELECT login,email FROM accounts WHERE login=?");
ps.setString(1, account);
ResultSet rs = ps.executeQuery();
while (rs.next())
{
if (rs.getString("login").equals(account))
{
email = rs.getString("email");
break;
}
}
Is there any other way except that while loop to retrieve data?
The if condition inside the while loop is completely redundant - the where clause takes care of it and assures that any data returned from this query would have a login field that's equal to the value of account.
If you're sure there's no more than one row like this (e.g., the login column is a unique identifier in your table), you could just replace the while loop with an if:
// Check that such a logic exists
if (rs.next()) {
email = rs.getString("email");
}
// for good measures, just double check there isn't more than one
// of these logins:
if (rs.next()) {
throw new Exception ("This cannot be!"); // Or something more sensible
}

SQL selected statement in Java

I am trying to get a specific result from my database by executing a query with a passed in parameter. Currently it's saying the result set is empty, and I know it shouldn't be because there is a row in the database that meets the 'where clause'. So I'm thinking it's a problem with my query statement as this is the first time I've queried the database from Java.
Here's the code for the query:
public ResultSet getWordNetPathResultsFromDatabase(double result) throws SQLException {
//System.out.println(words);
Statement statement = conn.createStatement();
ResultSet wordNetResults = statement.executeQuery("SELECT WORDNETRESULT FROM WORDNETSCORES WHERE LINRESULT = 'result'");
return wordNetResults;
}
Your result variable is a double-type. So no need for single quote in your query:
ResultSet wordNetResults = ("SELECT WORDNETRESULT FROM WORDNETSCORES WHERE LINRESULT = "+ result);
As esprittn mentioned, your query is supposed to return only those results where LINRESULT = result. Now, in your getWordNetPathResultsFromDatabase() function parameter, you have used result as a function parameter, and you have specified its data type as double. In your query, you are not actually trying to return a double value, but a string named 'result'. That's why it was creating confusions.
You can do any one of the following two things.
Either:
public ResultSet getWordNetPathResultsFromDatabase(double result) throws SQLException {
//System.out.println(words);
Statement statement = conn.createStatement();
ResultSet wordNetResults = statement.executeQuery("SELECT WORDNETRESULT FROM WORDNETSCORES WHERE LINRESULT = " + result);
return wordNetResults;
}
Here in order to return the result value using it inside your querystring, you must separate it from the query statement using a '+' sign. And this is the standard method.
Or if you want to return a string 'result', then you can do this:
public ResultSet getWordNetPathResultsFromDatabase(String s) throws SQLException {
//System.out.println(words);
Statement statement = conn.createStatement();
s = 'result';
ResultSet wordNetResults = statement.executeQuery("SELECT WORDNETRESULT FROM WORDNETSCORES WHERE LINRESULT = " + s);
return wordNetResults;
}
Depends on what exactly do you want to achieve as result. Choice is yours.

need to retrieve a database row value via sql based on values retrieved via previous sql query in java

My code goes something like this
DataBaseUtil dbBaseUtil=new DataBaseUtil();
Connection con=dbBaseUtil.getConnection();
String query="select case_id, ticket_id from VAPP_ITEM where
(person1_alt_email='" + username +"') and ticket_type='Service Request' and ticket_status not in ('Closed','Resolved')";
ResultSet rs=dbBaseUtil.getDbResultSet(query);
List<String> tickets=new ArrayList<String>();
while(rs.next())
ticket.add(rs.getString("case_Id")+"-"+rs.getString("ticket_Id"));
MyTicketUtil.searchAndOpenTicket(webui, "", tickets.get(0));
Now, once I get the element "tickets(0)", I perform some operations on it, and after the operations are performed, I need to retrieve ticket_status for the ticket on which the operations were performed - tickets(0).
However, to query the database, I need case_id and ticket_id for tickets(0). How can it be done?
I tried creating two ResultSets and a query post operations like below:
while(rs1.next())
quer1 = "select ticket_status from VAPP_ITEM where case_id=rs.getString(1) and ticket_id = rs.getString(2)";
But this is not working - console shows below error:
com.microsoft.sqlserver.jdbc.SQLServerException: Cannot find either column "rs" or the user-defined function or aggregate "rs.getString", or the name is ambiguous.
You have included rs.getString() into string literal.
You should use PreparedStatement for such things:
quer1 = "SELECT ticket_status FROM vapp_item WHERE case_id=? AND ticket_id = ?";
PreparedStatement pstm = conn.prepareStatement(quer1);
while (rs1.next())
{
pstm.setString(1, rs.getString(1));
pstm.setString(2, rs.getString(2));
rs2 = pstm.executeQuery();
...
}

Categories