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!
Related
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.
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.
I am writing a generic Java code and i want to add integers to a min Heap which will be stored in a mysql database. For that i have written below code,
public void addElement(Comparable value) {
sql = "INSERT INTO testHeap VALUES("+size+","+(int)value+ ") ";
try {
stmt.executeUpdate(sql);
size++;
} catch (SQLException ex) {
Logger.getLogger(HeapMySql.class.getName()).log(Level.SEVERE, null, ex);
}
if(size == 0) throw new IllegalStateException("Shape error");
int index = size - 1;
while(size != 0) {
sql = "SELECT value FROM testHeap WHERE indexnum ="+index;
T val;
try {
val = (T)stmt.executeQuery(sql);
if(myParent(index).compareTo(val) <= 0) break;
swap(parent(index), index);
index = parent(index);
} catch (SQLException ex) {
Logger.getLogger(HeapMySql.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
This returns below exception in runtime
Exception in thread "main" java.lang.ClassCastException: com.mysql.jdbc.JDBC4ResultSet cannot be cast to java.lang.Comparable
at Lab03.HeapMySql.addElement(HeapMySql.java:140)
I wan to know how to do this "val = (T)stmt.executeQuery(sql)" properly :)
You need to specify a column in the result set (even though there's only one)
val = (T)new Integer(stmt.executeQuery(sql).getInt(1));
As you commented below, you need an active row in your result set.
You also need to close it after you're done or you'll run out of database cursors. Reading past the last row (using rs.next) will automatically close it, so I use a "while" instead of an "if".
ResultSet rs = stmt.executeQuery(sql);
while (rs.next()) {
val = (T)new Integer(rs.getInt(1)))
}
The ResultSet has all results as an Object in an array, it's not the result itself! You have to cast every single one to the type it is. Furthermore the ResultSet can be used to make easy changes back to the database, too. So you didn't get the concept of jdbc at all ^^ You should read a few tutorials how to work with jdbc in general.
For further help please make your question better understandable. We can't know which line is 140 (from the error), i assume:
if(myParent(index).compareTo(val) <= 0) break;
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
so I'm trying to connect to a database using java.. there's a problem at a function I wrote getOutSymptoms.
Here's the code
package database_console;
import java.sql.*;
public class DBConnect {
private Connection con;
private Statement st;
private ResultSet rs;
public DBConnect(){
try {
Class.forName("com.mysql.jdbc.Driver");
try {
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/users", "root", "admin");
st = con.createStatement();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public int getOutSymptoms(int userID) throws SQLException{
String query = "SELECT `user`.`out_symptoms` FROM user WHERE (`user`.`id` =" + userID + ")";
rs = st.executeQuery(query);
int out_symptoms_value = rs.getInt("out_symptoms");
st.close();
return out_symptoms_value;
}
the error is at the getOutSymptoms function, at the line:
int out_symptoms_value = rs.getInt("out_symptoms");
why is that? and how can I fix it?
thank u so much.
You need to iterate through your result set in order to get the returned rows. When you first get your new ResultSet, it's not pointing to any particular row (its pointer is set to a row before first) and you need to call rs.next() method at least once to get to the actual results.
If you know there can be only one result you can do something like this:
if (rs.next()) {
int out_symptoms_value = rs.getInt("out_symptoms");
//do other stuff
} else {
//query returned no results
}
If you expect to have more than one row returned, then you can do this:
while(rs.next()) {
int out_symptoms_value = rs.getInt("out_symptoms");
//do the rest of processing
}
TLDR: You need to call rs.next() at least once to get to the actual results.
In order to start using a ResultSet, you must call the next() method. Although you haven't stated the exact error, you will definitely run into this problem unless it is added before you call getInt().
http://docs.oracle.com/javase/tutorial/jdbc/basics/retrieving.html
you need to iterate through the resultSet object using rs.next() to get the value. resultSet doesn't point to the actual row but when you call rs.next() it points to first result.
while(rs.next(){
int d = rs.getInt(" ");
}
rs.next() returns a boolean value , incase nothing is returned the loop will not execute & you will not get an Exception at runtime.
You have already passed the database name in connection string so change this
String query = "SELECT `user`.`out_symptoms` FROM user WHERE (`user`.`id` =" + userID + ")";
to
String query = "SELECT out_symptoms FROM tableName WHERE id =" + userID;
Then just iterate over the obtained ResultSet like this
while(rs.next()) {
int out_symptoms_value = rs.getInt("out_symptoms");
}
Moreover its good to use PreparedStatement instead of Statement which cna prevent you from sql injection
i'm trying to get the type and the name of the result and when enter in the loop, excuting somo instructions about the metadata the resulset.next changed from true to false, and give the error java.sql.SqlExcepcion exhausted resultset. Any ideas? i really dont know how solved it because i read the post with the solution of this problem and validate if the resultset it's null before begin the loop. I'm called this method with a scheduler of quartz. I'm using this in a j2ee aplication and the example it's this
try
{
InitialContext ctx = new InitialContext();
WrapperDataSource wrapperDataSource = (WrapperDataSource)ctx.lookup(systemLogger.getConfigurationParameters().getDataSource());
conn = wrapperDataSource.getConnection();
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver").newInstance();
conn = DriverManager.getConnection(url,login,password);
if (conn != null)
{
stmt = conn.createStatement();
res = stmt.executeQuery(query);
if (res != null)
{
while (res.next())
{
for (int i = 0; i < columnlength; i++)
{
String columnName = metadata.getColumnName(i+1);
if (metadata.getColumnName(i+1).equalsIgnoreCase(systemLogger.getColumnStatus()))
{
columnStatusType = metadata.getColumnType(i+1);
}
else if (metadata.getColumnName(i+1).equalsIgnoreCase(systemLogger.getColumnDocumentId()))
{
columnDocumentIdType = metadata.getColumnType(i+1);
}
else if (metadata.getColumnName(i+1).equalsIgnoreCase(systemLogger.getColumnTimer()))
{
columnTimerType = metadata.getColumnType(i+1);
}
}
}
}
else
{
__log.error("No results found for the query");
throw new PtmServiceException("No se encontraron resultados para el query");
}
}
else
{
__log.error("Could not create the connection");
throw new PtmServiceException("No se pudo crear la conexion");
}
}
catch(Exception e)
{
__log.error("Error in the execution of the query");
throw new PtmServiceException("Error ejecutando la busqueda");
}
finally
{
res.close();
stmt.close();
conn.close();
}
The variable columnlength seems to hold a value larger than the number of columns returned by the query. Try with a smaller columnlength.
finally, i see the problem, while i'm debugging the code with ecplise in the view of the expressions i added the follow expression res.next(), then each sentence that i pass for the step into bring the consequence that expression that evaluate if the resultset has more rows, be evaluated again. In some point the resultset has evaluated all the rows for each step into that i made in the process of debugging. The only thing that i have to do was eliminate the expression and works fine...
The problem might not be with the code but instead could be the database. Double check that the TABLE IS NOT EMPTY. You get this error if the table is empty. Keep in mind that databases like Oracle require a commit after all your insert, update, alter statements .Your changes might not be visible outside the database till you run a commit over the your db, I was having this problem for quite a long time. I kept on checking the table with select statement but the problem with my oracle db was that I had not issued a commit over my db.