Query returing no results codename one - java

Query showing no results and not giving any error .control not entering inside the if block help me out that where is the mistake i am doing ?
i have tried many ways to get the result but all in vain. When i tried the following before the if statement
int column=cur.getColumnCount();
Row row=cur.getRow();
row.getString(0);
then i got the resultset closed exception
Database db=null;
Cursor cur=null;
System.out.print("Printing from accounts class "+Email+Password);
String [] param={Email,Password};
System.out.print(param[0]+param[1]);
try{
db=Display.getInstance().openOrCreate("UserAccountsDB.db");
cur= db.executeQuery("select * from APPUserInfo WHERE Email=? AND Password=?",(String [])param);
int columns=cur.getColumnCount();
if(columns > 0) {
boolean next = cur.next();
while(next) {
Row currentRow = cur.getRow();
String LoggedUserName=currentRow.getString(0);
String LoggedUserPassword=currentRow.getString(1);
System.out.println(LoggedUserName);
next = cur.next();
}
}
}catch(IOException ex)
{
Util.cleanup(db);
Util.cleanup(cur);
Log.e(ex);
}
finally{
Util.cleanup(db);
Util.cleanup(cur);
}

As #jobin said in the comments the cursor to the result appears before the first entry so until you invoke next() for the first time you don't have access to the data.
It seems that the table is empty which means there is no user in the DB matching email/password. Try removing the email/password clause to get a list of all the users to verify.

Related

SQL check if table contains value?

I´m new to SQL. My goal is, to create a program, which should check whether a certain table has a certain value. I´ve wrote this method
public boolean existString(final String query) {
try {
final Statement statement = this.conn.createStatement();
result = statement.executeQuery(query);
return true;
} catch(SQLException e) {
e.printStackTrace();
return false;
}
}
As you can see, its a method for executing a SQL-statement. I think this may be the right statement :
String query = "select * from table where column1 = 'checkvalue'"; // of course i need to replace table and column and checkvalue
But atfer executing this statement, how can I prove if it was successfull (Does the query return something)? If the statement, after executing would return something, I could easly use a if-statement to check.
A SQL statement can return successfully if there are no rows returned from the database, so using a SQLException is not going to help you if the query is correct but there is no match.
public boolean existString(final String query) {
try {
final Statement statement = this.conn.createStatement();
result = statement.executeQuery(query);
return result.next();
} catch(SQLException e) {
e.printStackTrace();
return false;
}
}
You should leverage the fact that result.next() attempts to move the result pointer to the next row and return whether or not there is a row to return. This way, if successful and there is results ir returns true and of successful and not results, it returnsfalse. If something goes wrong, you're exception handling will take care of hte rest.
Yes, your method and SQL query are enough for checking. If there is no row output in the query, it will be null.

Why does my for loop in android studio stop after the first iteration?

I created a system in which I can run all my postgre sql queries with only one single Async Task Class in Android Studio. This was really(!!) challenging due to the big amount of limitations that I had to face. But this works actually really great!
//Used for connecting to database and executing queries.
//Index 0 of input string must be the query, Index 1 must be the tablename we demand
//We can only gather data from 1 table for each query, so if you need data from several tablecolumns, use multiple queries like:
//[0] = query, [1] = tablename, [2] = 2nd query, [3] = 2nd tablename, [4] = 3rd query, [5] = 3rd table name ... and so on (each query must come with a tablename)
public class DBHandler extends AsyncTask<String, Void, List<String>>
{
public AsyncResponse delegate;
#Override
protected List<String> doInBackground(String...query)
{
List<String> result = new ArrayList<String>();
String sql;
String tableresult = null;
Connection conn = null;
Statement st = null;
ResultSet rs = null;
try {
Class.forName("org.postgresql.Driver");
conn = DriverManager.getConnection("jdbc:postgresql://192.168.200.300:5439/dbname?user=anonymous&password=secretpw");
st = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE); //necessary if you want to use rs.first() after rs.next(), it makes the resultset scrollable
for (int i = 0; i <= query.length-1; i = i+2) //queries are always stored in i=0 and/or in i+2, because i+1 contain the demanded tablenames for resultset handling
{
System.out.println("I is: " +i);
if (!query[i].isEmpty())
{
System.out.println(query[i]);
sql = query[i];
rs = st.executeQuery(sql);
while (rs.next())
if (!query[i + 1].isEmpty() || !rs.getString(query[i + 1]).isEmpty()) //if i+1 is empty, there is no demanded tablename. Used when we dont need any return values (ie. INSERT, UPDATE)
result.add(rs.getString(query[i + 1])); //demanded tablename is always stored in i+1
//We add an empty entry if we demand multiple tablenames so we can keep them seperate
//Might be replaced with any other char, but you will have to backtrack all usages of DBHandler and fix the filters there
if(i+2 < query.length)
result.add(" ");
}
rs.first(); //reset pointer for rs.next()
}
rs.close();
st.close();
conn.close();
System.out.println("End of AsyncTask");
}
catch (SQLException ex)
{
ex.printStackTrace();
}
catch (Exception e)
{
e.printStackTrace();
}
return result;
}
//onPostExecute returns query result in a List.
//We need to use interaces delegate feature to send the result to other classes, like "Auslieferung", which is implementing the interface
#Override
protected void onPostExecute(List<String> result)
{
super.onPostExecute(result);
System.out.println("Result: " +result.toString());
if (!result.isEmpty())
delegate.processFinish(result);
}
}
There is a for-loop in this Async Task.
for (int i = 0; i <= query.length-1; i = i+2)
And now finally I can explain my issue:
I usually use SELECT queries, sometimes I use an INSERT query (which can be done by a single query), but when I parse an Update Query, my for-loop stops iterating after the first pass, so i+2 never happens. The update queries look like this:
String updatequeries[] = {UPDATE delivery SET contactperson = 'Jon Doe' WHERE officeid = 5, " ", UPDATE delivery SET contactemail = 'abd#def.gh' WHERE officeid = 5, " "};
Why does this for loop stop running right after the first run? The debugger does not show anything unusual, everything was parsed right and there are no queries missing. Updating a table does not return any results, but nothing depends on result values here. I tried to run 20 update queries in a single string var, but the for loop stops after the first iteration anyway. No issues are displayed in the debugger or in the logs. Have I overseen something or is there anything I don't know? Might this be a bug? Please help me! This issue drives me crazy.

Java -> Mysql: get INT doesnt work?

In my DB theres a field named 'failcounter' and its an int.
Which query i have to use to receive the int?
i tried with:
SELECT `failcounter` FROM `randomstuff`
and tried to receive the int with:
if(zrs.next()){
return zrs.getInt(1);
}else{
return -99;
}
but im not able to get the int.
Whats wrong? =)
Here is the whole method, maybe theres something wrong:
public static int getFailCounter() throws Exception {
try {
// This will load the MySQL driver, each DB has its own driver
Class.forName("com.mysql.jdbc.Driver");
// Setup the connection with the DB
connect = DriverManager.getConnection(""+MyBot.mysqlDbPath+"",""+MyBot.mysqlDbUsername+"",""+MyBot.mysqlDbPassword+"");
PreparedStatement zpst=null;
ResultSet zrs=null;
zpst=connect.prepareStatement("SELECT `failcounter` FROM `randomstuff`");
zrs=zpst.executeQuery();
if(zrs.next()){
return zrs.getInt(1);
}else{
return -99;
}
}catch (Exception e) {
throw e;
} finally {
close();
}
}
From your comment I always get -99
It means that ,
if(zrs.next()){
return zrs.getInt(1);
}
doesnt gets executed . Also understand the differences using if(zrs.next()) and while(zrs.next())
You usually use "while" as you want to loop through all the data in the result set. You use "if" when the query returns one row by definition
So in your case the ResultSet must be null or the column index might be wrong . so check for the Data in the table first
Hope this helps !
Try you this.
ResultSet res = st.executeQuery("SELECT * FROM event");
while (res.next())
{
int id = res.getInt("id");
String msg = res.getString("msg");
System.out.println(id + "\t" + msg);
}
And follow more read [How to connect with MySQL database using Java
Read more: http://mrbool.com/how-to-connect-with-mysql-database-using-java/25440#ixzz30N93JAkm]1
Best of Luck!

how to set values from database into the textfield

private void btgetinvActionPerformed(java.awt.event.ActionEvent evt) {
//JOptionPane.showMessageDialog(null, "REMITTANCE ID IS VALID!");
try {
DBUtil util = new DBUtil();
Connection con = util.getConnection();
PreparedStatement stmt = con.prepareStatement("select bk_det.rm_id from bk_det WHERE dbo.bk_det.rm_id = ?");
ResultSet rs;
String rm = tf_rmid.getText().trim();
stmt.setInt(1, Integer.parseInt(rm));
rs = stmt.executeQuery();
while (rs.next()) {
int i = Integer.parseInt(rs.getString("box_no"));
tfbrname.setText(rs.getString(i));
}
} catch (Exception ex) {
JOptionPane.showMessageDialog(null, ex.getMessage());
}
}
I am actually trying to search value from my database table called dbo.bk_det. I am taking the value of WHERE from my textfield tf_rmid. Everything goes on well without error but once i insert the rm_id and click on button btgetinv it says 123 which is my rm_id is out of range cant understand where the error is and what is the problem.
The problem is with the following statements:
int i = Integer.parseInt(rs.getString("box_no"));
tfbrname.setText(rs.getString(i));
The first statement won't work the way you want because there's no column named "box_no" in the select clause. It will throw an exception. Let's assume you change the code to have box_no in the select clause. Then, the second statement will try to retrieve the nth column where the column is the value of box_no. I think you just want:
tfbrname.setText(rs.getString("box_no"));
Again, the above only will work if your SELECT statement includes box_no in the field list.
rs.next() returns false if it does not contain any more records. So if you want to behave something when no records found, you have to check record count.
for example,
int recordCount = 0;
while (rs.next()) {
recordCount++;
int i = Integer.parseInt(rs.getString("box_no"));
tfbrname.setText(rs.getString(i));
}
if(recordCount == 0) {
// do something : report an error or log
}
for further information, see http://docs.oracle.com/javase/7/docs/api/java/sql/ResultSet.html#next()

Java MySQL get last row

So I'm having issues with my program. Basically this far the program is like a MySQL based chat. It stores messages in database and reads them. I'm having problems with the reading. What it does right now is ever 5 seconds re-read all the messages in the database. I tried to make it read only the new messages but that's not working out too well. This is my code:
public static void readChat()
{
try
{
MySQL.sqlConnect();
try
{
Statement st = con.createStatement();
ResultSet res = st.executeQuery("SELECT * FROM table1");
while (res.next())
{
if (lastLine < res.getInt("id"))
{
String message = res.getString("message");
Gui.out.append(message + "\n");
lastLine = res.getInt("id");
}
}
}
catch (SQLException s)
{
System.out.println("SQL code does not execute.");
}
MySQL.sqlDisconnect();
}
catch (Exception e)
{
e.printStackTrace();
}
}
I'm not sure how to make this efficient. It takes way too long to execute that. If the id is 23 I can't even see the messages appear because it takes longer than 5 seconds. I added the
if (lastLine < res.getInt("id"))
and
lastLine = res.getInt("id");
in my effort to make it read only the new messages but it did not work as expected. I think it still executed line by line, just doesn't show it in the chat. There's got to be an easier way.
EDIT: Alright, so I fixed the problem with not seeing messages, (I forgot to remove the part of the code that cleared the chat every 5 seconds). But it still takes a long time to send messages, about 3-4 seconds?
Try this, and you will wonder :)
ResultSet res = st.executeQuery("SELECT * FROM table1 where id > "+lastLine);
instad
ResultSet res = st.executeQuery("SELECT * FROM table1");
and get result without if
while (res.next())
{
String message = res.getString("message");
Gui.out.append(message + "\n");
lastLine = res.getInt("id");
}
Of course make sure index on id field
you can just read the required rows, currently you are reading all the rows try following,
public static void readChat()
{
try
{
MySQL.sqlConnect();
try
{
Statement st = con.Preparestatment("SELECT * FROM table1 where id > ?");
st.setInt(0,lastLine);
ResultSet res = st.executeQuery();
while (res.next())
{
String message = res.getString("message");
Gui.out.append(message + "\n");
lastLine = res.getInt("id");
}
}
catch (SQLException s)
{
System.out.println("SQL code does not execute.");
}
MySQL.sqlDisconnect();
}
catch (Exception e)
{
e.printStackTrace();
}
}
You still iterate through all results. If you have some way of storing the time at which messages are sent i.e creating a time column, you can try to shorten how many results are returned by doing
ResultSet res = st.executeQuery("SELECT * FROM table1 WHERE id = ? AND time > ?");
where the first ? is the id of the user and the 2nd ? is the time of the last read message. This is based off the assumption id is some unique user id.
What about maintaining a list, add new message to that list when you save it to the database and just read the new messages from that list and clear it at the end of readChat()?

Categories

Resources