I created this code to allow me calculate the number of rows in my table. However, I'm not able to return the counted number with an error saying "cannot return a value from method whose result type is void." Could someone show me where' my error? Thanks alot!
public void num() 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("jdbc:mysql://localhost/testdb?"
+ "user=root&password=");
// Statements allow to issue SQL queries to the database
statement = connect.createStatement();
resultSet = statement.executeQuery("select * from testdb.emg");
int count = 0;
while (resultSet.next()) {
count++;
}
return count;
} catch (Exception e) {
}
Try below code
public int num() 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("jdbc:mysql://localhost/testdb?"
+ "user=root&password=");
// Statements allow to issue SQL queries to the database
statement = connect.createStatement();
resultSet = statement.executeQuery("select count(*) from testdb.emg");
while (resultSet.next()) {
return resultSet.getInt(1);
}
} catch (Exception e) {
}
Below were error
public void num() throws Exception {
should be
public int num() throws Exception {
For counting total rows you should use query select count(*) from testdb.emg
Let me know incase of any problem.
Change
public void num() throws Exception {
to
public int num() throws Exception {
You are returning value from variable count which is of type int therefore the return type of the method should be int as well.
You should also make sure there is a return statement in every execution path through your code including the exception handler in the catch blocks (or you will get a "missing return statement" error message). However, it is best to avoid catch statements which catch all exceptions (like yours). Also, ignoring (i.e. not handling) exceptions in the catch block often leads to hard to diagnose problems and is a bad practice.
There are also other problems with the code: with the exception of count none of your variables have been declared.
Note that you may use the following SQL statement to obtain the number of rows directly:
select count(*) from testdb.emg
This avoids sending all of the data from table testdb.emg to your application and is much faster for big tables.
How to get count(*) mysql data table in java.
TRY IT:
public int getRowNumber(){
int numberRow = 0;
Connection mysqlConn = DriverManager.getConnection(HOST, USER_ID, PASSWORD);
try{
mysqlConn.getConnection();
String query = "select count(*) from dataTable";
PreparedStatement st = mysqlConn.preparedStatement(query);
ResultSet rs = st.executeQuery();
while(rs.next()){
numberRow = rs.getInt("count(*)");
}
}catch (Exception ex){
System.out.println(ex.getMessage());
}
return numberRow;
}
public void num() throws Exception {
should be
public int num() throws Exception {
I use Fahim Parker answer with a bit change
`
public int num() throws Exception {
try {
Class.forName("com.mysql.jdbc.Driver");
connect = DriverManager.getConnection("jdbc:mysql://localhost/testdb?"
+ "user=root&password=");
statement = connect.createStatement();
resultSet = statement.executeQuery("<your query statement>");
resultSet.last(); //go to last row;
return resultSet.getRow(); //get row number which is equal to rows count
} catch (Exception e) {
}
`
Related
I trying to make a connection to my DDBB in order to print all the columns from a table but I keep getting Null.
I have checked the connection parameters and everything seems correct.
I'm thinking that maybe there is something wrong with my query statement:
public List<Palabra> getTodos() throws SQLException {
SQLConexion con = new SQLConexion();
listaPalabras = new ListaPalabras();
if(con.ConectarBasedeDatos()) {
try{
Statement stmt = con.getConnection().createStatement();
ResultSet rs=stmt.executeQuery("SELECT * FROM PALABRA");
while(rs.next()) {
Palabra pal = new Palabra(rs.getInt("idPalabra"), rs.getString("palabra"), rs.getInt("dificultad")); //These are the columns that I need to print.
listaPalabras.addPalabra(pal); //adding the results to the list
}
}
catch(Exception e)
{
System.out.println(e);
}
}
else {
return null;
}
con.DesconectarBasedeDatos();
return listaPalabras.getListaPalabras();
}
I managed to solve the problem by adding the MySQL Connector to the libraries so indeed there was no connection with the database because of this.
Novice error.
Thanks a lot for your time.
I was wondering how to issue a MySQL command that checks if a table within my database is empty and then subsequently store the boolean result into a java variable. I am trying to use JDBC commands to do this.
This is what I have so far but it is not working properly:
#Override
public boolean isEmpty(Connection connection) {
Statement statement = null;
ResultSet resultSet = null;
Boolean var = true;
try {
statement = connection.createStatement();
System.out.println(statement.execute("SELECT EXISTS (SELECT 1 FROM Persons) AS OUTPUT"));
if(statement.execute("SELECT EXISTS (SELECT 1 FROM Persons)")) {
var = false;
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
statement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
return var;
}
When I run the program with a completely new, unpopulated mySQL table, the function returns true. Does anyone know a solution?
Your test checks if the table exists, instead you want to see if the table contains any rows. In order to do so, select the count of rows from the table and verify it is greater than 0. Prefer PreparedStatement over Statement (it's more efficient and performant), and you need a ResultSet to actually iterate the result from the server. Something like,
#Override
public boolean isEmpty(Connection connection) {
PreparedStatement statement = null;
ResultSet resultSet = null;
boolean res = false; // no need for the wrapper type here.
String sql = "SELECT COUNT(*) FROM Persons";
try {
statement = connection.prepareStatement(sql);
System.out.println(sql);
resultSet = statement.executeQuery();
if (resultSet.next()) {
res = resultSet.getInt(1) > 0;
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
resultSet.close();
} catch (SQLException e) {
e.printStackTrace();
}
try {
statement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
return res;
}
Changed var to res because (as of Java 10) var is now a keyword in Java.
As you are executing a select statement, instead of using Statement.execute(..), you should use Statement.executeQuery(..) and iterate over its result set.
The boolean return value from execute(..) indicates if the first value is a result set or not. It is not the boolean column from your query. You should normally only use execute(..) if you don't know what type of statement it is, or if it is a statement that can produce multiple results (update counts and result sets).
So, instead use:
boolean exists;
try (ResultSet rs = statement.executeQuery("SELECT EXISTS (SELECT 1 FROM Persons)")) {
exists = rs.next() && rs.getBoolean(1);
}
Hey guys I'm trying to get the value from mySQL MAX function (trying to get highest customer ID) and store it in a variable in my java code. Can't seem to get the thing to work.
public static int findMaxID() {
int maxID = 0;
String updateStmt =
"SELECT #maxID := MAX(idCustomer)\n" +
"FROM customers\n";
try {
DBUtil.dbExecuteQuery(updateStmt);
System.out.println(maxID);
} catch (SQLException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
return maxID;
}
Use a statement, ideally a prepared statement:
int maxID = 0;
String sql = "SELECT MAX(idCustomer) AS max_id FROM customers";
PreparedStatement ps = conn.prepareStatement(sql);
ResultSet rs = ps.executeQuery();
if (rs.next()) {
int maxID = rs.getInt("max_id"); // access the max value via its alias
}
While your current query might be valid MySQL, the session variable #maxID is only available on MySQL and not in your Java code. To access it you would need to yet again write another query.
I'm attempting to grab the size of a ResultSet. Now because I'm using SQLite, and SQLite only supports TYPE_FORWARD_ONLY cursors I'm trying to figure out how to grab it's size without throwing an error. This wont work:
int size = 0;
rs.last();
size = rs.getRow();
Nor can I use a prepared statement to change the cursor to scroll-able. Are Is there anyway to get the size?
I've also tried creating a while loop method to handle this and it still doesn't seem to to work
public static int getResultSetSize(ResultSet rs) throws SQLException{
int size = 0;
while(rs.next()){
size++;
}
return size;
}
Any help would be appreciated.
EDIT:
I've tried the following with no success
ResultSet rs = DBHelpers.getResultSet("SELECT COUNT(*) FROM USERS;");
int count = 0;
try {
count =rs.getInt(0) ;
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
The helper method for that is as follow:
public static ResultSet getResultSet(String sql){
ResultSet rs = null;;
try (Statement stmt = conn.createStatement()){
rs = stmt.executeQuery(sql);
} catch (SQLException e) {
System.out.println(e.getMessage());
return null;
}
return rs;
}
Conn is static connection variable initialized elsewhere in the program to point to the proper database and it has not caused any problems.
You should map your result to an entity. Create a list of those entities, and then simply get the size of the list.
If you want the size and the size only, then simply make a query to return a count of the result of your original query.
The column begins with index 1.
Try this...
Removes the semicolon from your query
ResultSet rs = DBHelpers.getResultSet("SELECT COUNT(*) FROM USERS");
And then
while (rs.next()) {
System.out.println(rs.getInt(1));
}
Instead of
count =rs.getInt(0);
Do a count on the database for the same query...SELECT Count(*) your query....
Run that before you do your query and you should have the size of your result set.
i am trying to add two methods to withdraw and deposit money in Bank Class . My Database name is javatest . table name is bank and following is the code . Problem is that when i run this code compiler says You have an error in your SQL syntax; i did check code 3-4 times but really unable to get it please help me with it .
public static void main(String[] args)
{
Connection connection= null ;
Statement stmt = null ;
try
{
Class.forName("com.mysql.jdbc.Driver");
connection= DriverManager.getConnection("jdbc:mysql://localhost:3306/javatest","root","");
stmt= connection.createStatement();
withdrawfromchecking(connection, stmt, new BigDecimal(100), 1);
Depositinsaving(connection, stmt, new BigDecimal(444), 1);
stmt.executeBatch();
System.out.println("Done");
}
catch (ClassNotFoundException e) {e.getMessage();}
catch (SQLException e) {e.printStackTrace();}
finally
{
if(connection!=null){try {connection.close();} catch (SQLException e) {e.printStackTrace();}}
if(stmt!=null){try {stmt.close();} catch (SQLException e) {e.printStackTrace();}}
}
}
public static void withdrawfromchecking(Connection connection ,Statement stmt, BigDecimal amount , int id ) throws SQLException
{
stmt.addBatch("UPDATE bank SET checkingbalance = checkingbalance-"+amount+"WHERE id="+id);
}
public static void Depositinsaving(Connection connection ,Statement stmt, BigDecimal amount , int id ) throws SQLException
{
stmt.addBatch("UPDATE bank SET savingbalance = savingbalance+ "+amount+"WHERE id="+id);
}
}
Error comes for this line - stmt.executeBatch(); when i run program
EDIT : Exact error statement
java.sql.BatchUpdateException: You have an error in your SQL syntax;
check the manual that corresponds to your MySQL server version for the
right syntax to use near 'id =1' at line 1 at
com.mysql.jdbc.StatementImpl.executeBatch(StatementImpl.java:1193) at
MyPackage.BankAccount.main(BankAccount.java:24)
in my code (line 24 is stmt.executeBatch();
In both of your SQLs, there is no space between the concatenation of the amount and the word WHERE -- it looks like this: checkingbalance-100WHERE id=.
Place a space before both WHERE words.
stmt.addBatch("UPDATE bank SET checkingbalance = checkingbalance-"
// +- Add space here
// v
+amount+" WHERE id="+id);
Change your withdrawfromchecking and Depositinsaving methods to this:
public static void withdrawfromchecking(Connection connection, Statement stmt, BigDecimal amount, long id) throws SQLException{
statement.addBatch("UPDATE bank SET checkingBalance = checkingBalance - " +amount+ " WHERE id =" + id);
}
public static void Depositinsaving(Connection connection, Statement stmt, BigDecimal amount, long id) throws SQLException{
statement.addBatch("UPDATE bank SET savingBalance = savingBalance + " +amount+ " WHERE id =" + id);
}
The first step would be to put the update statement in a string and examine the value after concatenation.
Ideally you should be using parameterized prepared statements instead of dynamically concatenating the sql.