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.
Related
This is my code and i was trying to update 2 tables.But only one table updates with this code. And no error messages appear as well.
Code:
DefaultTableModel RecordTable = (DefaultTableModel)jTable1.getModel();
int selectedRow = jTable1.getSelectedRow();
String sql ="UPDATE `sales` SET `Username`=?,`Type`=?,`Size`=?,`Unit_Price`=?,`Quantity`=?,`Total`=? WHERE `Type`=?";
String sql2 ="UPDATE `orders` SET `Username`=?,`Total`=? WHERE `Username`=? AND `Total` ";
try {
pst =dbConnection.getConnection().prepareStatement(sql);
String type = jComboBox_type.getSelectedItem().toString();
String size =jComboBox_size.getSelectedItem().toString();
String qty = jSpinner1.getValue().toString();
String tot = String.valueOf(total);
String uprice = String.valueOf(price);
int grstot = Integer.parseInt(jTextField_finaltot.getText())-Integer.parseInt(RecordTable.getValueAt(selectedRow, 4).toString());
finaltotal = grstot +total;
jTextField_finaltot.setText(String.valueOf(finaltotal));
String u = jTextField_usn.getText();
RecordTable.setValueAt(type,jTable1.getSelectedRow(),0);
RecordTable.setValueAt(size,jTable1.getSelectedRow(),1);
RecordTable.setValueAt(uprice,jTable1.getSelectedRow(),2);
RecordTable.setValueAt(qty,jTable1.getSelectedRow(),3);
RecordTable.setValueAt(tot,jTable1.getSelectedRow(),4);
pst.setString(1, u);
pst.setString(2,type );
pst.setString(3,size );
pst.setString(4,uprice);
pst.setString(5,qty );
pst.setString(6,tot);
pst.setString(7, type);
result =pst.executeUpdate();
pst2 =dbConnection.getConnection().prepareStatement(sql2);
pst2.setString(1, u);
pst2.setString(2,tot);
pst2.setString(3,u);
pst2.setString(4,tot);
JOptionPane.showMessageDialog(null,"Record Updated");
} catch (SQLException ex) {
Logger.getLogger(Pizza_Menu.class.getName()).log(Level.SEVERE, null, ex);
}
I was unable to sort out the problem here. please help to find out it!
I am using a mysql table, and now I need to compare a columns all values with a given String.
I want to check if all values of the result set matches with encryptedString.
Need to understand what result set does and how it works.
Here I have a method, Some variables, and 2 mysql queries.
final String secretKey = "!!!!";
String name = jText.getText();
String pass = jTextPass.getText();
String originalString = pass;
String encryptedString = AES.encrypt(originalString, secretKey) ;
String decryptedString = AES.decrypt(encryptedString, secretKey) ;
PreparedStatement PS;
ResultSet result;
String query1 = "SELECT `pass` FROM `Remember_Pass` WHERE `name` =?";
PreparedStatement ps;
String query;
query = "UPDATE `tutor profile` SET `pass`=? WHERE `name`=?";
try {
PS = MyConnection.getConnection().prepareStatement(query1);
PS.setString(1, name);
PS.setString(2, encryptedString);
rs = PS.executeQuery();
//while(result.next() ){
//I am not understanding what to do here.
ps = MyConnection.getConnection().prepareStatement(query);
ps.setString(1, encryptedString);
ps.setString(2, name);
ps.executeUpdate();
PassSuccess success = new PassSuccess();
success.setVisible(true);
success.pack();
success.setLocationRelativeTo(null);
this.dispose();
//}
} catch (SQLException ex) {
Logger.getLogger(ForgetPassT.class.getName()).log(Level.SEVERE, null, ex);
}
First tip: using try-with-resources closes statement and result set even on exception or return. This also reduces the number of variable names for them because of the smaller scopes. This return from the innermost block I utilized. For unique names one can use if-next instead of while-next. A fail-fast by not just logging the exception is indeed also better; you can exchange the checked exception with a runtime exception as below, so it easier on coding.
String query1 = "SELECT `pass` FROM `Remember_Pass` WHERE `name` = ?";
String query = "UPDATE `tutor profile` SET `pass`=? WHERE `name`= ?";
try (PreparedStatement selectPS = MyConnection.getConnection().prepareStatement(query1)) {}
selectPS.setString(1, name);
//selectPS.setString(2, encryptedString);
try (ResultSet rs = selectPS.executeQuery()) {}
if (result.next()){ // Assuming `name` is unique.
String pass = rs.getString(1);
try (PreparedStatement ps = MyConnection.getConnection().prepareStatement(query)) {
ps.setString(1, encryptedString);
ps.setString(2, name);
int updateCount = ps.executeUpdate();
if (updateCount == 1) {
PassSuccess success = new PassSuccess();
success.setVisible(true);
success.pack();
success.setLocationRelativeTo(null);
return success;
}
}
}
}
} catch (SQLException ex) {
Logger.getLogger(ForgetPassT.class.getName()).log(Level.SEVERE, null, ex);
throw new IllegalStateException(e);
} finally {
dispose();
}
the ResultSet object contains all the information about the query that you perform, it will contain all columns. In your code the result variable will return anything since there is no part in your code where is executed, to do this you have to...
Statement statement = MyConnection.getConnection().createStatement();
ResultSet result = statement.executeQuery("YOUR SELECT STATEMENT HERE");
while(result.next()){
String column1 = result.getString("columnName");
}
The result.next() method is a boolean method that says if the ResultSet object still have values of the table inside and it will continue until it reaches the last row that your SELECT statement retrives. Now if you want to match the value of some column with other variables you can do it inside the while(result.next()).
result.getString("columnName") will extract the value from columnName as a String.
If you want to save things in an ArrayList to save the data and then use this list as you want the code can be like...:
Statement statement = MyConnection.getConnection().createStatement();
ResultSet result = statement.executeQuery("YOUR SELECT STATEMENT HERE");
List<Object> data = new ArrayList();
while(result.next()){
data.add(result.getString("columnName"));
}
return data;
Obviously you have to change the Object with the type of things that you want to store in the List.
Or if you want to store the data in an array. As I said in my comment this won't be dinamic, but...:
Statement statement = MyConnection.getConnection().createStatement();
ResultSet result = statement.executeQuery("YOUR SELECT STATEMENT HERE");
String[] data = new String[NUMBER_OF_COLUMNS_IN_RESULTSET];
while(result.next()){
data[0] = result.getString("columnName1");
data[1] = result.getString("columnName2");
data[2] = result.getString("columnName3");
//And so on...
}
return data;
The other way is that if you are returning an entity you can set the values of the ResultSet directly in the POJO:
Statement statement = MyConnection.getConnection().createStatement();
ResultSet result = statement.executeQuery("YOUR SELECT STATEMENT HERE");
Entity entity = new Entity();
while(result.next()){
entity.setColumnName1(result.getString("columnName1"));
entity.setColumnName2(result.getString("columnName2"));
entity.setColumnName3(result.getString("columnName3"));
//And so on...
}
return entity;
There are so many ways to store the data, just ask yourself how do you want to receive the data in the other parts of you code.
Regards.
I would like to check the database for duplicates before inserting into the database. It is only considered a duplicate when plateNo, driverID and resDate match.
Here is how I get the data that will be inserted to the database
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
String client = (String) clientCmb.getSelectedItem();
String[] cparts = client.split("-");
String cpart = cparts[0];
String driver = (String) driverCmb.getSelectedItem();
String[] dparts = driver.split("-");
String dpart = dparts[0];
String van = (String) vanCmb.getSelectedItem();
java.util.Date oDate = jXDatePicker2.getDate();
DateFormat oDateFormat = new SimpleDateFormat("yyyy-MM-dd");
String date = oDateFormat.format(oDate);
model2.addRow(cpart, dpart, van, date);
}
And here's the code for my addRow method
public void addRow(String client, String driver, String van, String res){
try {
String sqlRes = "Select * from reservation";
rs = st.executeQuery(sqlRes);
rs.moveToInsertRow();
rs.updateString("clientID", client);
rs.updateString("plateNo", van);
rs.updateString("driverID", driver);
rs.updateString("resDate", res);
rs.insertRow();
rs.moveToCurrentRow();
rs = st.executeQuery(sqlRes);
this.fireTableDataChanged();
} catch (SQLException ex) {
Logger.getLogger(MyModel2.class.getName()).log(Level.SEVERE, null, ex);
}
Let the database do the work for you. Define a unique index/constraint specifying that those three values are unique in the table:
create unique index unq_reservation_3 on reservation(plateNo, driverID, resDate);
If you attempt to insert a duplicate -- or do an update that results in a duplicate -- then the database will return an error. You simply need to catch the error.
Use MERGE statement: T-SQL or ORACLE, or for MySQL:
PreparedStatement p = con.prepareStatement("
INSERT INTO reservation tgt (clientID, plateNo, driverID, resDate)
SELECT (? As clientID, ? As plateNo, ? As driverID, ? As resDate)
FROM DUAL ins
LEFT JOIN reservation ref
ON ref.resDate = ins.resDate
AND (ref.plateNo = ins.plateNo OR ref.driverID = ins.driverID)
WHERE ref.clientID IS NULL;
");
p.setString(1, client);
p.setString(2, van);
p.setString(3, driver);
p.setString(4, res);
return p.executeUpdate(); /* 1 - Success | 0 - Ignored Duplicate */
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");
I'm having an issue where my GUI program is showing no error and also not updating the jTable with the UPDATE statement I'm giving it. INSERT and DELETE are working fine, but this isn't for some reason.
I'm using UCanAccess so I can use an MSAccess DB and rs2xml for resultset stuff.
The table I'm modifying here is a junction table with 2 primary keys for director_id and movie_id which are linked to separate tables so this is a many-to-many relationship.
private void jButtonEditActionPerformed(java.awt.event.ActionEvent evt) {
DefaultTableModel tableModel = (DefaultTableModel) jTableDBView.getModel();
// If there's an issue...
if(error handling snipped out...)
{
}
else
{
runQuery(Integer.parseInt(jTextFieldDirectorID.getText()), Integer.parseInt(jTextFieldMovieID.getText()), "UPDATE");
jTextAreaDBView.append("Updated row: " + (jTableDBView.getSelectedRow() + 1) + " (Director ID: " + jTextFieldDirectorID.getText() + " & Movie ID: " + jTextFieldMovieID.getText() +")\n");
updateDB();
}
Which calls...
public void runQuery(int movieID, int directorID, String typeOfCommand) throws SQLException
{
Connection conn = DriverManager.getConnection(jdbcURL);
ResultSet rs = null;
PreparedStatement stat = null;
try
{
//snipped insert/delete
else if(typeOfCommand.equals("UPDATE"))
{
stat = conn.prepareStatement("UPDATE Movie_Directors SET director_id = ?, movie_id = ? WHERE (director_id = ?) AND (movie_id = ?)");
stat.setInt(1, directorID);
stat.setInt(2, movieID);
stat.setInt(3, directorID);
stat.setInt(4, movieID);
int result = stat.executeUpdate();
}
And
private void updateDB()
{
try
{
Connection conn = DriverManager.getConnection(jdbcURL);
PreparedStatement pst = conn.prepareStatement(query);
Class.forName(driver);
ResultSet rs = pst.executeQuery();
jTableDBView.setModel(DbUtils.resultSetToTableModel(rs)); // Imported lib function
conn.close();
pst.close();
rs.close();
}
catch (Exception ex)
{
// Add a window here
}
}
UPDATE - Fixed the runQuery block with this: I added 2 new jTextFields to input the new data and I understand how it all works now. Thank you #jan
int result;
int newDirectorID = Integer.parseInt(jTextFieldNewDirectorID.getText());
int newMovieID = Integer.parseInt(jTextFieldNewMovieID.getText());
stat = conn.prepareStatement("UPDATE Movie_Directors SET director_id = ?, movie_id = ? WHERE director_id = ? AND movie_id = ?");
stat.setInt(1, newDirectorID);
stat.setInt(2, newMovieID);
stat.setInt(3, directorID);
stat.setInt(4, movieID);
result = stat.executeUpdate();
I might be mistaken - but your update does nothing. It assigns (movieId, directorId) to that row which already has exactly that (movieId,directorId)
So if there is already a row - nothing happens. And if there's no matching row - nothing happens as well.
An update would make sense if for instance a movie's director did change at some time.
In that case, you'd need a variable newDirectorID and put it in as new value:
int newDirectorID; // YOU NEED TO PROVIDE A VALUE
stat = conn.prepareStatement("UPDATE Movie_Directors SET director_id = ?, movie_id = ? WHERE director_id = ? AND movie_id = ?");
stat.setInt(1, newDirectorID);
stat.setInt(2, movieID);
stat.setInt(3, directorID);
stat.setInt(4, movieID);
int result = stat.executeUpdate();
This would infact change some data in your table, so number of updated rows should be 1 if (directorID, movieID) existed before.