Null Exception error when retriving null image from database [duplicate] - java

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 7 years ago.
I am using MySQL to store and retrieve data, including 1 picture.
In my Java application, Users are supposed to insert a picture, but this is optional. So if a user does not insert a picture and I try to retrieve all the data from my database, there is a null pointer exception error.
I want to display an empty image or a default image if the image retrieved from the database is null.
This is my code.
//This is the data access to add and retrieve from the database.
private static Medication convertToMedication(ResultSet rs) throws SQLException {
Medication med;
int id=rs.getInt("idMedicationInfo");
String diseaseName = rs.getString("diseaseName");
String medicationName = rs.getString("medicationName");
byte[] image = rs.getBytes("medPic");
if (image==null){
}
double initialMedAmt = rs.getDouble("initialAmount");
double servingSize = rs.getDouble("servingSize");
boolean morning=rs.getBoolean("morning");
boolean afternoon=rs.getBoolean("afternoon");
boolean evening=rs.getBoolean("night");
med=new Medication( diseaseName, medicationName,image, initialMedAmt, servingSize, morning, afternoon, evening);
return med;
}
public static boolean createMedication(Medication med){
// declare local variables
boolean success = false;
DBController db = new DBController();
String dbQuery;
PreparedStatement pstmt;
// step 1 - establish connection to database
db.getConnection();
// step 2 - declare the SQL statement
dbQuery = "INSERT INTO medicationinfo(diseaseName, medicationName , medPic ,initialAmount,servingSize,amountLeft,morning,afternoon,night) VALUES(?,?,?,?,?,?,?,?,?);";
pstmt = db.getPreparedStatement(dbQuery);
//pstmt = db.getPreparedStatement(dbQuery);
// step 3 - to insert record using executeUpdate method
try {
pstmt.setBytes(3, med.getMedPic());
pstmt.setDouble(4, med.getInitialMedAmt());
pstmt.setDouble(5, med.getServingSize());
pstmt.setDouble(6, med.getAmountLeft());
//pstmt.setDouble(8, med.getmedicationServingSize());
pstmt.setBoolean(7, true);
pstmt.setBoolean(8, true);
pstmt.setBoolean(9, true);
if (pstmt.executeUpdate() == 1){
success = true;
}
pstmt.close();
} catch(Exception e){
e.printStackTrace();
}
// step 4 - close connection
db.terminate();
return success;
}
public static ArrayList<Medication> retrieveAllMedication(){
// declare local variables
ArrayList<Medication> list = new ArrayList<Medication>();
ResultSet rs;
DBController db = new DBController();
String dbQuery;
// step 1 - connect to database
db.getConnection();
// step 2 - declare the SQL statement
dbQuery = "SELECT * FROM medicationinfo";
// step 3 - using DBController readRequest method
rs = db.readRequest(dbQuery);
try {
while (rs.next()){
Medication med = convertToMedication(rs);
list.add(med);
}
}catch (Exception e){
e.printStackTrace();
}
// step 4 - close connection
db.terminate();
return list;
}
public static Medication retrieveMedicationById(int id){
// declare local variables
Medication med = null;
ResultSet rs = null;
DBController db = new DBController();
String dbQuery;
PreparedStatement pstmt;
// step 1 - connect to database
db.getConnection();
// step 2 - declare the SQL statement
dbQuery = "SELECT * FROM expense WHERE id = ?";
pstmt = db.getPreparedStatement(dbQuery);
// step 3 - execute query
try {
pstmt.setInt(1, id);
rs = pstmt.executeQuery();
if (rs.next()){ // first record found
med = convertToMedication(rs);
}
} catch (Exception e){
e.printStackTrace();
}
// step 4 - close connection
db.terminate();
return med;
}
public static ArrayList<Medication> retrieveMedicationByMorning(){
// declare local variables
ArrayList<Medication> list = new ArrayList<Medication>();
ResultSet rs = null;
DBController db = new DBController();
String dbQuery;
PreparedStatement pstmt;
// step 1 - connect to database
db.getConnection();
// step 2 - declare the SQL statement
dbQuery = "SELECT * FROM medicationinfo WHERE morning = ?";
pstmt = db.getPreparedStatement(dbQuery);
// step 3 - execute query
try {
while (rs.next()){
Medication med = convertToMedication(rs);
list.add(med);
}
}catch (Exception e){
e.printStackTrace();
}
// step 4 - close connection
db.terminate();
return list;
}
public static ArrayList<Medication> retrieveMedicationByAfternoon(){
// declare local variables
ArrayList<Medication> list = new ArrayList<Medication>();
ResultSet rs = null;
DBController db = new DBController();
String dbQuery;
PreparedStatement pstmt;
// step 1 - connect to database
db.getConnection();
// step 2 - declare the SQL statement
dbQuery = "SELECT * FROM medicationinfo WHERE afternoon = ?";
pstmt = db.getPreparedStatement(dbQuery);
// step 3 - execute query
try {
while (rs.next()){
Medication med = convertToMedication(rs);
list.add(med);
}
}catch (Exception e){
e.printStackTrace();
}
// step 4 - close connection
db.terminate();
return list;
}
public static ArrayList<Medication> retrieveMedicationByEvening(){
// declare local variables
ArrayList<Medication> list = new ArrayList<Medication>();
ResultSet rs = null;
DBController db = new DBController();
String dbQuery;
PreparedStatement pstmt;
// step 1 - connect to database
db.getConnection();
// step 2 - declare the SQL statement
dbQuery = "SELECT * FROM medicationinfo WHERE evening = ?";
pstmt = db.getPreparedStatement(dbQuery);
// step 3 - execute query
try {
while (rs.next()){
Medication med = convertToMedication(rs);
list.add(med);
}
}catch (Exception e){
e.printStackTrace();
}
// step 4 - close connection
db.terminate();
return list;
}

Check first if the rs.getBytes is null or not.
byte[] image = null;
if (rs.getBytes("medPic") != null)
image = rs.getBytes("medPic");

Related

Illegal operation on empty result set. using LAST_INSERT_ID()

I'm trying to get the last created id in my table with the LAST_INSERT_ID() function, in a java code, but it does not work.
Here is my sql code :
public static int lastInsertID() {
int lastBillId = 0;
try {
Connexion conn = new Connexion();
Statement stm = (Statement) conn.obtenirConnexion().createStatement();
ResultSet res = stm.executeQuery("SELECT bill_id FROM bill WHERE bill_id = LAST_INSERT_ID()");
res.next();
lastbillId= res.getInt("bill_id");
} catch (Exception e) {
e.printStackTrace();
}
return lastBillId;
}
Here is my database bill
Here is my error
And it sends me 0 as result.

how to fix "This ResultSet is closed " error?

I want to use two sql query in my java code. the first query retain all row of table2 and the second one get it's rows one by one. I wrote follow code but it face to "This ResultSet is closed, it means rs ResultSet " error. How can I fix?
try{
String sqlSelectTable2 = "SELECT * FROM table2;";
ResultSet rs = stmt.executeQuery(sqlSelectTable2);
while (rs.next()) {
String strLineId = rs.getString(1);
String strPoints = rs.getString(2);
String sqlWithin = "SELECT ST_Within(ST_GeometryFromText('POINT( ),ST_GeomFromText('POLYGON((443425 4427680, 441353 4427680, 441368 4426075, 443762 4426149, 443425 4427680))', 4326));";
ResultSet rsWithin = stmt.executeQuery(sqlWithin);
} // end while ... **It get error when it is reading second ResultSet **
} catch (Exception e) {
System.out.println(e.getMessage());
}
You need to create separate PreparedStatement object for inner query
try{
String sqlSelectTable2 = "SELECT * FROM table2;";
ResultSet rs = stmt.executeQuery(sqlSelectTable2);
while (rs.next()) {
String strLineId = rs.getString(1);
String strPoints = rs.getString(2);
PreparedStatement preparedStatement = null;
String sqlWithin = "SELECT ST_Within(ST_GeometryFromText('POINT( ),ST_GeomFromText('POLYGON((443425 4427680, 441353 4427680, 441368 4426075, 443762 4426149, 443425 4427680))', 4326));";
preparedStatement = dbConnection.prepareStatement(sqlWithin);
ResultSet rsWithin = preparedStatement.executeQuery();
} // end while ... **It get error when it is reading second ResultSet **
} catch (Exception e) {
System.out.println(e.getMessage());
}

error in inserting data to database

Here's my code for createFood DA so that can insert to database. However , there is a nullPointerException at
pstmt.setString(2, food.getFoodName());
public static int createFood(Food food) {
// declare local variables
int orderID ;
DBController db = new DBController();
String dbQuery;
PreparedStatement pstmt;
// step 1 - establish connection to database
db.getConnection();
// step 2 - declare the SQL statement
dbQuery = "INSERT INTO orderitems (orderId, foodName, foodPrice, quantity,) VALUES(?,?,?,? )";
pstmt = (PreparedStatement) db.getPreparedStatement(dbQuery);
orderID = getNextOrderId();
// step 3 - to insert record using executeUpdate method
try {
pstmt.setInt(1,orderID );
pstmt.setString(2, food.getFoodName());
pstmt.setDouble(3 ,food.getFoodPrice());
pstmt.setInt(4, food.getQuantity());
if (pstmt.executeUpdate() == 1)
return orderID;
pstmt.close();
} catch (Exception e) {
e.printStackTrace();
}
// step 4 - close connection
db.terminate();
return -1;
}
This is the code when i click on "orders".
private void actionPerformedOrder() {
//retrieve user input
String numPax = (String) cbNoPax.getSelectedItem();
String tableNo= (String)cb_tableno.getSelectedItem();
java.util.Date utilDate = new java.util.Date();
Date orderDate = new Date(utilDate.getTime());
System.out.println("Date " + orderDate);
orders = new Orders(Integer.parseInt(tableNo),Integer.parseInt(numPax), (java.sql.Date) orderDate, totalAmount);
int orderID = OrdersDA.createOrders(orders);
OrderItems od;
for (Food fd: foodList) {
od = new OrderItems(orderID, fd.getFoodName(), fd.getQuantity(), fd.getFoodPrice());
FoodDA.createFood(food);
}
I still cannot figure out the error. Anyone knows where went wrong ? Much help will be appreciated.
You have passed createFood() method food variable which i cant see declare anywhere
try
createFood(fd) according to your code.

ResultSet not open. Operation 'moveToInsertRow' not permitted. Verify that autocommit is OFF

i'm having a trouble with this error, when i clicked the button, it'll take the values of the labels and put it in the table from database
void showAll(){
try{
rs1 = stmt.executeQuery("SELECT * FROM BORROW_RETURN");
while(rs1.next())
{
String bookpp = rs1.getString("name");
String emailse = rs1.getString("email");
String booktee = rs1.getString("book_title");
String ser_no = rs1.getString("serial_no");
String borr = rs1.getString("borrowed");
String ret = rs1.getString("return");
loginModel3.addRow(new Object[]{bookpp, emailse, booktee, ser_no, borr, ret});
}}catch(SQLException err){
System.out.print(err);
}
}
and this is the connection to the connection to the database
void DoConnect1( ) {
try{
String host = "jdbc:derby://localhost:1527/Dafuq7";
String uName ="Dafuq7";
String uPass ="Dafuq7";
con = DriverManager.getConnection(host, uName, uPass);
//EXECUTE SOME SQL AND LOAD THE RECORDS INTO THE RESULTSET
stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_UPDATABLE);
String sql = "SELECT * FROM borrow_return";
rs1 = stmt.executeQuery(sql);
}
catch (SQLException err) {
System.out.println(err.getMessage() );
}
}
and upon clicking the button the said error occurs,
private void jButton6ActionPerformed(java.awt.event.ActionEvent evt) {
String ema = jLabel20.getText();
String enm = jLabel21.getText();
String booknm = bttl.getText();
String snnnn = sernum.getText();
dateFormat = new SimpleDateFormat("yyyy-MM-dd");
String dates = dateFormat.format(date_borr.getDate());
try {
rs1.moveToInsertRow();
rs1.updateString( "book_title", booknm );
rs1.updateString( "serial_no", snnnn );
rs1.updateString( "name", enm );
rs1.updateString( "email", ema );
rs1.updateString( "borrowed", dates );
JOptionPane.showMessageDialog(null, "HAHA");
loginModel3.addRow(new Object[]{names, booknm, snnnn, enm, ema, dates});
con.setAutoCommit(false);
System.out.println(con.getAutoCommit());
rs1.insertRow( );
stmt.close();
rs1.close();
stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE);
String sql = "SELECT * FROM accounts";
rs1 = stmt.executeQuery(sql);
}
catch (SQLException err) {
System.out.println(err.getMessage() );
}
}
You are setting autoCommit to false after your queries are really committed. You need to set it false once after you open connection or before start executing your queries.
con = DriverManager.getConnection(host, uName, uPass);
//EXECUTE SOME SQL AND LOAD THE RECORDS INTO THE RESULTSET
stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_UPDATABLE);
String sql = "SELECT * FROM borrow_return";
con.setAutoCommit(false);
rs1 = stmt.executeQuery(sql);
https://codedump.io/share/WK0Jtw7GEH3h/1/why-do-i-get-javasqlsqlexception-resultset-not-open-operation-39next39-not-permitted-java-derby-database
By default, only one ResultSet object per Statement object can be open at the same time. Therefore, if the reading of one ResultSet object is interleaved with the reading of another, each must have been generated by different Statement objects. All execution methods in the Statement interface implicitly close a statment's current ResultSet object if an open one exists.

Java - Getting Data from MySQL database

I've connected to a MySQL database, which contains four fields (the first of which being an ID, the latter ones each containing varchar strings).
I am trying to get the last row of the database and retrieve the contents of the fields so that I can set them to variables (an int and three strings) and use them later.
So far, I have the bare minimum to make the connection, where do I go from here? As you can see I have tried to write a SQL statement to get the last row but it's all gone wrong from there and I don't know how to split it into the separate fields.
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection con = DriverManager.getConnection("jdbc:mysql://localhost/t", "", "");
Statement st = con.createStatement();
String sql = ("SELECT * FROM posts ORDER BY id DESC LIMIT 1;");
st.getResultSet().getRow();
con.close();
Here you go :
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection con = DriverManager.getConnection("jdbc:mysql://localhost/t", "", "");
Statement st = con.createStatement();
String sql = ("SELECT * FROM posts ORDER BY id DESC LIMIT 1;");
ResultSet rs = st.executeQuery(sql);
if(rs.next()) {
int id = rs.getInt("first_column_name");
String str1 = rs.getString("second_column_name");
}
con.close();
In rs.getInt or rs.getString you can pass column_id starting from 1, but i prefer to pass column_name as its more informative as you don't have to look at database table for which index is what column.
UPDATE : rs.next
boolean next()
throws SQLException
Moves the cursor froward one row from its current position. A
ResultSet cursor is initially positioned before the first row; the
first call to the method next makes the first row the current row; the
second call makes the second row the current row, and so on.
When a call to the next method returns false, the cursor is positioned
after the last row. Any invocation of a ResultSet method which
requires a current row will result in a SQLException being thrown. If
the result set type is TYPE_FORWARD_ONLY, it is vendor specified
whether their JDBC driver implementation will return false or throw an
SQLException on a subsequent call to next.
If an input stream is open for the current row, a call to the method
next will implicitly close it. A ResultSet object's warning chain is
cleared when a new row is read.
Returns:
true if the new current row is valid; false if there are no more rows Throws:
SQLException - if a database access error occurs or this method is called on a closed result set
reference
Something like this would do:
public static void main(String[] args) {
Connection con = null;
Statement st = null;
ResultSet rs = null;
String url = "jdbc:mysql://localhost/t";
String user = "";
String password = "";
try {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection(url, user, password);
st = con.createStatement();
rs = st.executeQuery("SELECT * FROM posts ORDER BY id DESC LIMIT 1;");
if (rs.next()) {//get first result
System.out.println(rs.getString(1));//coloumn 1
}
} catch (SQLException ex) {
Logger lgr = Logger.getLogger(Version.class.getName());
lgr.log(Level.SEVERE, ex.getMessage(), ex);
} finally {
try {
if (rs != null) {
rs.close();
}
if (st != null) {
st.close();
}
if (con != null) {
con.close();
}
} catch (SQLException ex) {
Logger lgr = Logger.getLogger(Version.class.getName());
lgr.log(Level.WARNING, ex.getMessage(), ex);
}
}
}
you can iterate over the results with a while like this:
while(rs.next())
{
System.out.println(rs.getString("Colomn_Name"));//or getString(1) for coloumn 1 etc
}
There are many other great tutorial out there like these to list a few:
http://www.vogella.com/articles/MySQLJava/article.html
http://www.java-samples.com/showtutorial.php?tutorialid=9
As for your use of Class.forName("com.mysql.jdbc.Driver").newInstance(); see JDBC connection- Class.forName vs Class.forName().newInstance? which shows how you can just use Class.forName("com.mysql.jdbc.Driver") as its not necessary to initiate it yourself
References:
http://zetcode.com/databases/mysqljavatutorial/
This should work, I think...
ResultSet results = st.executeQuery(sql);
if(results.next()) { //there is a row
int id = results.getInt(1); //ID if its 1st column
String str1 = results.getString(2);
...
}
Easy Java method to get data from MySQL table:
/*
* CREDIT : WWW.CODENIRVANA.IN
*/
String Data(String query){
String get=null;
try{
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection con = (Connection)DriverManager.getConnection
("jdbc:mysql://localhost:3306/mysql","root","password");
Statement stmt = (Statement) con.createStatement();
ResultSet rs=stmt.executeQuery(query);
if (rs.next())
{
get = rs.getString("");
}
}
catch(Exception e){
JOptionPane.showMessageDialog (this, e.getMessage());
}
return get;
}
Here is what I just did right now:
import java.sql.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import com.sun.javafx.runtime.VersionInfo;
public class ConnectToMySql {
public static ConnectBean dataBean = new ConnectBean();
public static void main(String args[]) {
getData();
}
public static void getData () {
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/mynewpage",
"root", "root");
// here mynewpage is database name, root is username and password
Statement stmt = con.createStatement();
System.out.println("stmt " + stmt);
ResultSet rs = stmt.executeQuery("select * from carsData");
System.out.println("rs " + rs);
int count = 1;
while (rs.next()) {
String vehicleType = rs.getString("VHCL_TYPE");
System.out.println(count +": " + vehicleType);
count++;
}
con.close();
} catch (Exception e) {
Logger lgr = Logger.getLogger(VersionInfo.class.getName());
lgr.log(Level.SEVERE, e.getMessage(), e);
System.out.println(e.getMessage());
}
}
}
The Above code will get you the first column of the table you have.
This is the table which you might need to create in your MySQL database
CREATE TABLE
carsData
(
VHCL_TYPE CHARACTER(10) NOT NULL,
);
First, Download MySQL connector jar file, This is the latest jar file as of today [mysql-connector-java-8.0.21].
Add the Jar file to your workspace [build path].
Then Create a new Connection object from the DriverManager class, so you could use this Connection object to execute queries.
Define the database name, userName, and Password for your connection.
Use the resultSet to get the data based one the column name from your database table.
Sample code is here:
public class JdbcMySQLExample{
public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/YOUR_DB_NAME?useSSL=false";
String user = "root";
String password = "root";
String query = "SELECT * from YOUR_TABLE_NAME";
try (Connection con = DriverManager.getConnection(url, user, password);
Statement st = con.createStatement();
ResultSet rs = st.executeQuery(query)) {
if (rs.next()) {
System.out.println(rs.getString(1));
}
} catch (SQLException ex) {
System.out.println(ex);
}
}

Categories

Resources