I am trying to change one of the value in my table in database based on an another value in the same database but different table. The first table is called orders and the second is called buy supply. What I want to do is I want to change the value of sumquantity that is in 'buysupply' table by subtracting a value from the column named quantity_ordered from 'orders' table. I tried writing some query but it is not working, it keeps popping up error. If you know of a solution, do let me know. The code is all below as well
private void DispatchButtonActionPerformed(java.awt.event.ActionEvent evt) {
String type = txttype.getSelectedItem().toString();
String name = txtname.getText();
String quantity = txtquantity.getText();
String dispatch_row = txtdispatch.getText();
String statusDispatched = "Dispatched";
try {
Class.forName("com.mysql.jdbc.Driver");
con1 = DriverManager.getConnection("jdbc:mysql://localhost/restock", "root", "password");
// Focus on this
String template = "UPDATE orders SET status = '%s' WHERE id = %s";
String template2 = "UPDATE buysupply SET sumquantity = sumquantity - %s WHERE id = %s";
String quantity_ordered = "quantity_ordered FROM orders";
pst = con1.prepareStatement(String.format(template, statusDispatched, dispatch_row));
pst.executeUpdate();
pst1 = con1.prepareStatement(String.format(template2, quantity_ordered , dispatch_row));
pst1.executeUpdate();
// Look on top
JOptionPane.showMessageDialog(null, "Item has been dispatched");
// To update the newly recorded data to the table
table_update();
// Set the textfields to empty upon button click
txttype.setSelectedIndex(-1);
txtname.setText("");
txtquantity.setText("");
txtdispatch.setText("");
txttype.requestFocus();
} catch (ClassNotFoundException | SQLException ex) {
JOptionPane.showMessageDialog(null, "Quantity or Dispatch field is not an integer, Please try again.");
Logger.getLogger(mainpage.class.getName()).log(Level.SEVERE, null, ex);
}
}
// This code is in another class file
try {
Class.forName("com.mysql.jdbc.Driver");
con1 = DriverManager.getConnection("jdbc:mysql://localhost/restock", "root", "password");
String template = "SELECT SUM(quantity) as sumquantity FROM buysupply WHERE itemtype IN ('Plastic gloves', 'Rubber gloves')";
PreparedStatement pst = con1.prepareStatement(template);
ResultSet rs = pst.executeQuery();
if (rs.next()) {
glovesum = rs.getString("sumquantity");
} else {
System.out.print("Query didn't return any results");
}
} catch (ClassNotFoundException | SQLException ex) {
Logger.getLogger(stock.class.getName()).log(Level.SEVERE, null, ex);
}
As far I understand (and please read until the end) if it is a classic Invoice order database with a list of product into "buysupply" table and "order" table for the ordering client list of product.
The first point, several people into the comment point is the missing link data between both table. I assume reading your peace of code that the link is made by a ID but that not clear, so I offer a solution base on a link between those columns:
orders.itemtype = buysupply.itemtype
If it on an other element, please change the information into the SQL query below.
I assume also the column orders.status as to change the values from what I call 'Waiting' value to 'Dispatched' value.
So here the data before into "buysupply" table:
id, itemtype, quantity
1 , mask , 704
2 , clothed, 101
3 , N95, 18
Here the data before into "order" table:
id, itemtype, quantity_orderred, status,
1,mask, 1 , Dispatched
2,clothed,3,Waiting
The SQL to update both value (the orders.status and buysupply.quantity ) should be something like that suppose the order.id to update is 2:
update orders,buysupply
set orders.status='Dispatched',
buysupply.quantity = buysupply.quantity - orders.quantity_orderred
where
orders.itemtype = buysupply.itemtype
AND
orders.status = 'Waiting'
AND
orders.id = '2'
AFTER:
So here the data after into "buysupply" table:
id, itemtype, quantity
1 , mask , 704
2 , clothed, 98
3 , N95, 18
Here the data before into "order" table:
id, itemtype, quantity_orderred, status,
1,mask, 1 , Dispatched
2,clothed,3,Dispatched
The update could apply on several tables and columns, you should just indicate the column table name with each column to avoid confusion.
That could be the first step to let you improve the code for the sum part, that, I afraid no understand at all.
Then I find a partial information explaining that the sum_quantity is a computed calcul from a sum of the value, so you do not want to change the quantity, my bad.
So you can create a temporary table with this kind of SQL, temporary table is detroy at the connection close:
CREATE TEMPORARY TABLE IF NOT EXISTS TMPsumquantity AS
SELECT SUM(quantity) as sumquantity FROM buysupply WHERE itemtype IN ('Plastic gloves', 'Rubber gloves')
That could create a column with the information you want, BUT, it's not my recommendation as far I understand ;-)
I will create a new column to store the sum value into the table "buysupply", to say the "the quantity in stock avalaible at the moment this order will be Dispatched is that for this element" so the result of you sum value
Before "buysupply":
id, itemtype, quantity, quantity_avalaible
1 , mask , 704, 704
2 , clothed, 101, 101
3 , N95, 18, 18
Before "order":
id, itemtype, quantity_orderred, status, quantity_avalaible
1,mask, 1 , Dispatched
2,clothed,3, Waiting
So the SQL to create this column is complex, base on an inner-join between the same table
UPDATE buysupply b1
INNER JOIN (
SELECT SUM(quantity) as sumquantity, id
FROM buysupply
where buysupply.itemtype IN ('clothed', 'N95')
) b2 ON true
SET b1.quantity_avalaible = b2.sumquantity
So the new table "buysupply" with the colum "quantity_avalaible" containing the sum of the value of the colum quantity for N95 and clothed values :
id, itemtype, quantity, quantity_avalaible
1 , mask , 704, 116
2 , clothed, 101, 116
3 , N95, 18, 116
So then you can use the first SQL proposal to update quantity_avalaible depending the value of "orders.quantity_orderred"
Last point, I have a partial view on the data structure and the bussiness logic, it could be usefull to store a negative value into the column "orders.quantity_orderred" so the SQL SUM could add and substract values with the same call to the SUM function
Best
I am trying to fetch records from oracle db. I have a select query which has an order by clause implemented. Now when I fire the query on the toad i get the results in correct order. i.e the order of the records at 10:00 AM is like
Record 1, Record 2,Record 3 and at 10:05 its Record 1, Record 2, Record 3. This is what i need.
Now when iam fetching it through java code, JDBC . I try to iterate the resultset, but here at 10:05 am I am getting the order like Record 2, Record 1, Record 3. Due to this when i am adding the records to the arraylist the order is not mantained.
I dont want to sort the records of arraylist after adding.
Can someone please let me know why using jdbc the records are not fetched in the order we can see using toad ?
Sample code
try{
List<TestObjVO> testResults = new ArrayList<TestObjVO>();
double statusValue = 0;
//Connection code
pstmt = conn.prepareStatement(QUERY);
ResultSet rs = pstmt.executeQuery();
while (rs.next()) {
testObj = new TestObjVO();
String date = rs.getString(1);
String status = rs.getString(2);
String svc_nm= rs.getString(3);
if("SUCCESS".equalsIgnoreCase(status)){
statusValue = 1;
}else if("ERROR".equalsIgnoreCase(status)){
statusValue = -1;
}
testObj.setTime(date);
testObj.setStatus(statusValue);
testObj.setSvc_nm(svc_nm);
testResults.add(testObj);
}
SELECT query
SELECT to_char(PROBING_DATE,'DD-MM-YYYY HH24:MI:SS') AS PROBING_DATE, STATUS, SERVICE_NAME FROM TABLE_NAME WHERE PROBING_DATE >= (sysdate-30/1440) ORDER BY PROBING_DATE,SERVICE_NAME
Table
create table TABLE_NAME(
probing_date TIMESTAMP(6) not null,
status VARCHAR2(8) not null,
service_name VARCHAR2(128) not null
)
Change your select to something like this:
SELECT to_char(PROBING_DATE,'DD-MM-YYYY HH24:MI:SS') AS PROBING_DATE_STR,
PROBING_DATE,
STATUS,
SERVICE_NAME
FROM TABLE_NAME
WHERE PROBING_DATE >= (sysdate-30/1440)
ORDER BY PROBING_DATE,SERVICE_NAME;
Note there's an extra field returned and is the raw TIMESTAMP field.
How to retrieve data from two different MySQL database in a single query using jdbc?
SELECT
a.`driver_id`,
a.`state`,
a.`lat`,
a.`long`,
MAX(a.`time_stamp`) AS timestamp,
b.vehicle_type
FROM `rl_driv_location` AS a, `rl_driver_info` AS b
WHERE a.`state` = 1 AND a.`driver_id` = b.`user_id`
AND b.`vehicle_type` = '"+ cartype +"'
GROUP BY driver_id
location database having the rl_driv_location table.
core database having the rl_driver_info table.
Just specify the name of the databases where you want to retrieve data. See below.
SELECT
a.`driver_id`,
a.`state`,
a.`lat`,
a.`long`,
MAX(a.`time_stamp`) AS timestamp,
b.vehicle_type
FROM location.`rl_driv_location` AS a, core.`rl_driver_info` AS b
WHERE a.`state` = 1 AND a.`driver_id` = b.`user_id`
AND b.`vehicle_type` = '"+ cartype +"'
GROUP BY driver_id
I am new to mysql and I am trying to connect to the database using a Java Program and I am passing a mysql query.
public class dbconnect {
public static void main(String[] args) throws SQLException,ClassNotFoundException {
Class.forName("com.mysql.jdbc.Driver");
Connection conn =DriverManager.getConnection("jdbc:mysql://localhost:3306/mydatabase?user=root&password=root");
Statement st = conn.createStatement();
int custid= 0;
String myname = null;
String query = "select name from groups where customer_id = 2;";
//This query has a problem can anyone help me fix it.
System.out.println(query);
ResultSet rs1 = st.executeQuery(query);
System.out.println("after query");
while (rs1.next()){
custid = rs1.getInt("customer_id");
myname = rs1.getString("name");
System.out.println(myname);
System.out.println(custid);
}
}
}
I am passing a query "select name from groups where customer_id = 2" .
Here "name" is a coloumn,"groups" is a table and "customer_id" is another column. In the program when I give this query(no typos) I get the following error
Exception in thread "main" java.sql.SQLException: Column 'customer_id' not found.
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1073)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:987)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:982)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:927)
at com.mysql.jdbc.ResultSetImpl.findColumn(ResultSetImpl.java:1144)
at com.mysql.jdbc.ResultSetImpl.getInt(ResultSetImpl.java:2815)
at com.memoir.client.widgets.memogen.dbconnect.main(dbconnect.java:61)
I have checked with the table , customer_id is present in the table . They are no spelling mistakes also .Even then it says that customer_id column is not found .
Can anyone help me fix it.
The query needs to be:
String query = "select name, customer_id from groups where customer_id = 2;";
Honestly it doesn't make any sense, your query is
String query = "select name from groups where customer_id = 2;";
and you expect to get customer_id ??
as you are already passing customer_id in where clause you don't need to get it back again from db.
String query = "select customer_id,name from groups where customer_id = 2;";
The above would work with your current code .
You are accessing only name column in query and you are try to get "customer_id" in while loop from result set
while (rs1.next()){
custid = rs1.getInt("customer_id"); // **error is here - remove this line or change your query**
myname = rs1.getString("name");
System.out.println(myname);
System.out.println(custid);
}
Your problem is that you are trying to get an invalid column ("cutomer_id") from the result set which contains only the "name" column.
To resolve this you have to select also the "customer_id" in your query:
"select name, customer_id from groups where customer_id = 2";
custid = rs1.getInt("customer_id");
you result set does not have customer_id
Include that too in your query
try this
String mysqlquery = "select name, customer_id from groups where customer_id=2";
In PostgreSQL user is a reserved keyword that is used in an internal table, however I also have a separate user table in my own database that I need to use. Whenever I try to execute INSERT or UPDATE statements on the table, it generates the following error: The column name 'id' was not found in this ResultSet.
This is the Java code I am currently using:
PreparedStatement stat1 = conn.prepareStatement("SELECT id FROM user;");
PreparedStatement stat2 = conn.prepareStatement("UPDATE user SET date_created = ? , last_updated = ? , uuid = ? WHERE id = ?;");
ResultSet rs = stat1.executeQuery();
while(rs.next()){
UUID uuid = UUID.randomUUID();
String tempId = uuid.toString();
stat2.setTimestamp(1, curDate);
stat2.setTimestamp(2, curDate);
stat2.setString(3, tempId);
stat2.setLong(4,rs.getLong("id"));
stat2.executeUpdate();
}
So my question is, how could I insert or update the values in my personal user table without interfering with the keyword restriction?
Use this:
prepareStatement("UPDATE \"user\" set date_created = ?")
Or, better yet, rename your user table to something else, like users:
ALTER TABLE "user" RENAME TO users;
Escape the table name like this
select * from "user";