MySQL results of one table out of two not updating - java

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!

Related

I want to add a search in my sql database, function to get the name by the id creates an error

I have a music database so I'll need a search function, now when entering into the search bar, I get the error : "Invalid argument in JDBC call: parameter index out of range: 1"
public static Song getSongByName(String name)
{
String sql =
"SELECT songID FROM Song "+
"WHERE name = '?'; ";
Connection conn = Connections.getConnection();
Song erg = null;
try
{
PreparedStatement pstmt = conn.prepareStatement(sql);
pstmt.setString(1,name);
ResultSet rs = pstmt.executeQuery();
rs.next();
int id = rs.getInt (1);
name = rs.getString (2);
erg = new SongImpl(id,name);
rs.close();
pstmt.close();
}
catch(SQLException exc)
{
System.err.println("Fehler: in SQL-Aufruf");
System.err.println("["+sql+"]");
exc.printStackTrace();
System.exit(6);
}
Connections.putConnection(conn);
return erg;
}
It seems like you are selecting just one column instead of two.
The correct SQL query would be:
SELECT songID, songName FROM Song WHERE name = '?';
Try this:
public static Song getSongByName(String name)
{
String sql =
"SELECT songID, songName FROM Song "+
"WHERE name = ?";
Connection conn = Connections.getConnection();
Song erg = null;
try
{
PreparedStatement pstmt = conn.prepareStatement(sql);
pstmt.setString(1,name);
ResultSet rs = pstmt.executeQuery();
rs.next();
int id = rs.getInt(1);
String name = rs.getString(2);
erg = new SongImpl(id, name);
rs.close();
pstmt.close();
}
catch(SQLException exc)
{
System.err.println("Fehler: in SQL-Aufruf");
System.err.println("["+sql+"]");
exc.printStackTrace();
System.exit(6);
}
Connections.putConnection(conn);
return erg;
}
Let me know if that helped :)
Look onto examples https://docs.oracle.com/javase/tutorial/jdbc/basics/prepared.html
Try to remove single quotes:
String sql =
"SELECT songID FROM Song "+
"WHERE name = ?; ";
You should use string parameters without quotes because your statement interpreted as a SQL query without parameters.

display data from the same database colomn into 2 different jtable colomns using self join

I want to display data from the same database colomn into 2 different jtable colomns using that self join from the statement. I'm pretty sure my problem is somewhere here but I don't know how to solve it:
while (rs.next()) {
String d = rs.getString("a.nrzbor");
String e = rs.getString("b.nrzbor");
model.addRow(new Object[]{d, e});
jTable5.setModel(model);
}
Here is the full code:
String de_la = introducereOras1.getText();
String la = introducereOras2.getText();
DefaultTableModel model = new DefaultTableModel(new String[]{"nrzbor1", "nrzbor2"}, 0);
String url = "jdbc:mysql://localhost:3306/aeroport";
String user = "root";
String password = "";
PreparedStatement myStmt = null;
ResultSet rs = null;
try{
Connection myConn = DriverManager.getConnection(url, user, password);
myStmt = myConn.prepareStatement("SELECT a.nrzbor , b.nrzbor" +
"FROM Zboruri a,Zboruri b\n" +
"WHERE (a.de_la = ? AND b.de_la = ?) AND (a.la = ? AND b.la = ?);");
myStmt.setString(1, de_la);
myStmt.setString(2, la);
myStmt.setString(3, la);
myStmt.setString(4, de_la);
rs = myStmt.executeQuery();
while (rs.next()) {
String d = rs.getString("a.nrzbor");
String e = rs.getString("b.nrzbor");
model.addRow(new Object[]{d, e});
jTable5.setModel(model);
}
}
catch(Exception e){
System.err.println("Got an exception!");
System.err.println(e.getMessage());
}
Could anyone help me? Thanks!

How to check database for duplicates before inserting?

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 */

Fetch result SQL query data to Table JAVA

I want to make jtable display my result data from SQL query , the code like this
private void TampilTabel(){
String header[] = {"No","Nama","TTL","Usia"};
DefaultTableModel tabelku = new DefaultTableModel(null, header);
Object obj[] = new Object[10];
jTable1.setModel(tabelku);
TableColumnModel columnModel = jTable1.getColumnModel();
jTable1.setRowHeight(35);
try{
stat = (Statement) koneksiMySQL.GetConnection().createStatement();
String sql = "select No_Induk, Nama, Tgl_Lahir, \n" +
"(YEAR(CURDATE()) - YEAR(Tgl_Lahir)) - (RIGHT(CURDATE(),5) < RIGHT(`Tgl_Lahir`,5))\n" +
"AS Umur\n" +
"FROM tabel_pegawai ORDER BY Nama";
rst = stat.executeQuery(sql);
while (rst.next()){
obj[0] = rst.getString("No_Induk");
obj[1] = rst.getString("Nama");
obj[2] = rst.getString("Tgl_Lahir");
obj[3] = rst.getString("No_Induk");
tabelku.addRow(obj);
}
rst.close();
}catch(SQLException ex){
JOptionPane.showMessageDialog(rootPane, "Data Tidak Ada");
}
}
Question is how to get result data without use getString(), because in my database i didnt have 'Umur' row
Thanks before
Surely you want to do
obj[3] = rst.getString("Umur");
or you could simply do by column number
obj[3] = rst.getString(4);

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.

Categories

Resources