How to fetch MySQL data without creating Object from Class in Java - java

I want to fetch data from MySQL without creating object from class
Normally I do something like
public ArrayList getInventoryByItemId(String ItemId) throws SQLException {
ArrayList list = new ArrayList<Inventory>();
String sql = "SELECT iid, i.uid, item_data, item_id, i.ctime, username, gender FROM Inventory i JOIN user u ON i.uid = u.uid WHERE item_id = '"+ItemId+"'";
Statement stmt = con.createStatement();
ResultSet rset = stmt.executeQuery(sql);
while (rset.next()) {
a = new Inventory(rset.getInt(1), rset.getInt(2), rset.getString(3), rset.getString(4), rset.getTimestamp(6), rset.getString(7), rset.getString(8));
list.add(a);
}
return list;
}
the problem is because Inventory object does not have user data from the joined user table, I cannot create new Inventory.
I just want to automatically make an object where it has all the data attributes, that I can access using the column name.
Thank You

If I got you problem,
You can create new map(HashMap I reccomend) and put values using column name or index as key.
So, your list will be list of maps.
while (rset.next()) {
a = new HashMap<Integer,Object>();
a.put(1,rset.getInt(1));
..........
list.add(a);
}
Or, If you know exact number of columns, you can user array instead of Map (it will be faster)

Based on what you are saying, I take it that your query is not returning data because the inventory does not have the user data that it is being joined with. You need to modify your query to use a left outer join.
String sql = "SELECT iid, i.uid, item_data, item_id, i.ctime, username, gender FROM Inventory i LEFT JOIN user u ON i.uid = u.uid WHERE item_id = '"+ItemId+"'"
This will allow your query to return Inventory data even if the corresponding User data does not exist.

Related

How can I update the result set without removing the previous result from it

I am using jdbc to retrieve data from database. I have four different queries for that, however, the result of first query is used to get the data of second and fourth query. But, the resultset, gets updated as i run other queries. So is there any way that i can keep the resultset and add new results in it.
Here is my code:
class GetData{
String toDate;
String fromDate;
GetData(String d1,String d2) throws ClassNotFoundException, SQLException, ParseException, TransformerException, ParserConfigurationException {
toDate=d1;
fromDate=d2;
Connection connection= null;
ResultSet resultset= null;
String customerquery="SELECT o.ordernumber,o.orderdate,o.customernumber,c.customername,c.addressLine1,c.postalCode,c.city,c.country from orders o join customers c on o.customernumber=c.customernumber where orderdate between ? and ?";
String orderdetailquery="SELECT orderNumber,productCode,quantityOrdered,priceEach,orderLineNumber,(quantityOrdered * priceEach) as total FROM orderdetails where ordernumber=?";
String productsquery="SELECT productName,productLine,productVendor FROM products where productcode=?";
String employeequery="SELECT c.salesRepEmployeeNumber,e.firstname,e.lastname,o.officecode,o.city from customers c join employees e on c.salesRepEmployeeNumber = e.employeeNumber join offices o on e.officecode=o.officecode where c.customernumber=?";
Class.forName("com.mysql.cj.jdbc.Driver");
connection=DriverManager.getConnection("jdbc:mysql://localhost:3306/classicmodels","root","root");
if(d1!=null || d2!=null) {
PreparedStatement p1= connection.prepareStatement(customerquery);
p1.setString(1, toDate);
p1.setString(2,fromDate);
resultset= p1.executeQuery();
PreparedStatement p2= connection.prepareStatement(orderdetailquery);
while(resultset.next()) {
p2.setString(1, resultset.getString("orderNumber"));
}
resultset=p2.executeQuery();
PreparedStatement p3= connection.prepareStatement(productsquery);
while (resultset.next()) {
p3.setString(1, resultset.getString("productcode"));
}
resultset=p3.executeQuery();
PreparedStatement p4=connection.prepareStatement(employeequery);
while(resultset.next()) {
p4.setString(1, resultset.getString("customernumber"));
}
resultset=p4.executeQuery();
resultset.close();
connection.close();
}
}
I am trying to use the result of first query that contains the column customernumber to fetch the data. While, executing the code a error comes that customernumber column not found. So, how can I use the result of first query in other queries. Also, i am trying to get all the result of queries in one resultset as I am trying to create a xml out of it by using DOM.
You can put everything in a single query. using joins.
select o.ordernumber,o.orderdate
, o.customernumber,c.customername
, c.addressLine1,c.postalCode,c.city,c.country
, t1.productCode, t1.quantityOrdered, t1.priceEach, t1.orderLineNumber,(t1.quantityOrdered * t1. priceEach) as total
, t2.productName, t2.productLine, t2.productVendor
, c.salesRepEmployeeNumber,t4.firstname,t4.lastname,t3.officecode,t3.city
from orders o
join customers c on o.customernumber=c.customernumber
left join orderdetails t1 on t1.orderNumber = o.orderNumber
left join products t2 on t2.productCode = t1.productCode
left join offices t3 on t3.offiecode = c.customernumber
left join employees t4 on t3.officecode = t4.officecode
ResultSet is getting changed because you are using the same reference (object) every time you are executing the sql statement, hence it is overriding the old result, so if you want to deal with previously returned ResultSet, you can create new ResultSet instance to use, and also you can create a Bean class to set the elements and make it List type to keep on adding the results as per your logic.
Create a POJO to store required properties retrieved from different queries.
The resultset is getting updated because the same reference variable is being used to assign the resultset of subsequent queries.
If you want to use the same variable, you can follow like this -
create a POJO (which can be used to create a xml out of it by using DOM).
get result of first query in resultset.
populate relevant properties of POJO from this resultset.
re-use the resultset to store result of next queries.
When you need to use previous results, get them from the POJO to be used as parameters in subsequent queries.

Adding distinct data to jComboBox from database

I have a jComboBox which i want to fill up with the departments of the students in a database. Now the same department occurs many times in the table so i want each department name to go only once to the list of items. The present code i wrote is not giving the desired result. It puts the same department name multiple times on the ComboBox list. How can i solve this?
My code to fetch department names is given below:
conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/mydaatabase1","root","Password123");
String sql1 = "select distinct (dept) from droptest";
PreparedStatement pss = conn.prepareStatement(sql1);
ResultSet rs = pss.executeQuery(sql1);
while(rs.next())
{
String d = rs.getString("dept");
jComboBox1.addItem(d);
}
I guess, you need use group by in select data...
select columnName
from tablename
Group by columnName
Select dept
From droptest
Group by dept
Group by is like distinct

How to query database with in IN statement in Java?

I have a small app in which a user uploads a file which carries bunch of id's. I read the file and store all those id's in a list. Now for each id I need to query database so that I could select some other other info. My question is that how to incorporate those id's as part of select statement?
Currently I am querying manually just by typing the id and I want to know how to use getter() as part of query?
Method to select from database
public List<NYProgramTO> getLatestNYData() throws Exception {
String query = "SELECT REQ_XMl, SESSIONID, EXPIRATION_DATE, QUOTE_DATE, POLICY_EFFECTIVE_DATE, TARGET_CREATED, RATING_TRANSACTION_ID, SOURCE_LASTMODIFIED, PREM_WHEN_RERATED FROM dbo.XML_SESSIONS with (nolock) WHERE XML_SESSIONS.LOB = 'PersonalAuto' AND XML_SESSIONS.RATING_STATE = 'NY' AND XML_SESSIONS.ID IN ('72834052') ORDER BY XML_SESSIONS.SOURCE_LASTMODIFIED DESC";
return this.sourceJdbcTemplate.query(query, (rs, rowNum) -> {
NYProgramTO to = new NYProgramTO();
to.setRequestXML(rs.getString("REQ_XML"));
to.setExpirationDate(rs.getDate("EXPIRATION_DATE"));
return to;
});
}
Thanks
You can use MapSqlParameterSource to map the parameter.
public void selectExample(Car car){
String query = "select * from car where id_car = :id and color = :color";
this.sourceJdbcTemplate.query(query, new MapSqlParameterSource("id", car.getId()).addValue("color", car.getColor()), new CarRowMapper());
}

Merging three queries that use 1:* relationships into one query

Lets say i have four tables i want to read from:
customer
customer_id, customer_name
1 Joe Bolggs
customer_orders
customer_id, order_no
----------------------------
1 1
1 2
1 3
customer_addresses
customer_id address
----------------------------
1 11 waterfall road
1 23 The broadway
customer_tel_no
customer_id number
----------------------------
1 523423423432
1 234342342343
The customer information shown above (for the customer with id=1) is to be stored in a Java object as shown below
public class Customer{
String customer_id;
String customerName;
ArrayList<String> customerOrders;
ArrayList<String> customerAddress;
ArrayList<String> customerTelephoneNumbers;
}
The only way i can think of to get the above information is by using three queries. The reason is that there is a 1:* relationship between the customer table and each of the other tables. To get the data i am doing something like this:
Customer customer = new Customer()
String customerSQL = "Select * from customer where customer_id = ?";
statement = getConnection().prepareStatement(contactsQuery);
statement.setString(1,1);
resultSet = statement.executeQuery();
while (resultSet.next()){
customer.customer_id = resultSet.get(1); //No getters/setters in this example
customer.customerName = resultSet.get(2);
}
String customerOrdersSQL = "Select * from customer_orders where customer_id = ?";
statement = getConnection().prepareStatement(customerOrdersSQL);
statement.setString(1,1);
resultSet = statement.executeQuery();
customer.customerOrders = new ArrayList();
while (resultSet.next()){
customer.customerOrders.add(resultSet.getString(2); // all the order numbers
}
String customerAddressesSQL = "Select * from customer_addresses where customer_id = ?";
statement = getConnection().prepareStatement(customerAddressesSQL );
statement.setString(1,1);
resultSet = statement.executeQuery();
customer.customerAddresses = new ArrayList();
while (resultSet.next()){
customer.customerAddresses.add(resultSet.getString(2); // all the addresses
}
String customerTelSQL = "Select * from customer_tel_no where customer_id = ?";
statement = getConnection().prepareStatement(customerTelSQL);
statement.setString(1,1);
resultSet = statement.executeQuery();
customer.customerTelephoneNumbers = new ArrayList();
while (resultSet.next()){
customer.customerTelephoneNumbers.add(resultSet.getString(2); // all the order numbers
}
The problem with the above is that i am making three calls to the database. Is there a way i can merge the above into a single query please?
I cant see how a join would work because for example, a join between customer and customer_orders will return a customer row for each row in customer_orders. Is there anyway i can merge the above three queries into one?
I would think that something like this would work:
SELECT c.customer_id, c.customer_name, o.order_no, a.address, t.number
FROM customer c LEFT JOIN customer_orders o ON c.customer_id = o.customer_id
LEFT JOIN customer_addresses a ON c.customer_id = a.customer_id
LEFT JOIN customer_tel_no t ON c.customer_id = t.customer_id
WHERE c.customer_id = ?
Then, in your code, after you execute the query:
while (resultSet.next())
{
customer.customerOrders.add(resultSet.getString(3));
customer.customerAddresses.add(resultSet.getString(4));
customer.customerTelephoneNumbers.add(resultSet.getString(5));
}
Of course, this does not take into account the fact that you will have null values along the way, so I'd advise checking for nulls to make sure that you aren't adding a lot of junk to your array lists. Still, that's probably a lot less costly than 3 separate queries.
Nothing prevents you from iterating and processing the joined result into your customer object. If your application is complex enough, you could look into ORM frameworks which would do that for you under the covers. If you are working with JavaEE, have a look at JPA.
use this query and reduce the number of call. And, in while loop process on data.
select customer.customer_id,customer.customer_name,order_no,address,number
from customer,customer_orders,customer_addresses,customer_tel_no
where customer.customer_id = customer_orders.customer_id
AND
customer.customer_id = customer_addresses.customer_id
AND
customer.customer_id = customer_tel_no.customer_id

Datechooser for SQL query

I have two tables made in access. One table (Owner) contains: ownerID, name which owner has. Second table (Cars) contains: CarId, carname, year, ownerID they has relations between carid
In my java program I get from first table OwnerName and put them all into comboBox1
String sql="SELECT * FROM Owner ;";
ResultSet dane = zadanie.executeQuery(sql);
while(dane.next()) {
String OwnerId = dane.getString("OwnerID");
String OwnerName = dane.getString("OwnerName");
if (OwnerId != null) {OwnerId = OwnerId.trim();}
if (OwnerName != null) {OwnerName = OwnerName.trim();}
comboBox.addItem(OwnerId);
comboBox_1.addItem(OwnerName);
}
When I choose owner I want to have in combobox2 only these cars that have this owner.
Can someone suggest a solution?
I don't know exactly how to write the SQL statement to get that.
select tablename.carname from tablename where ownerID=SelectedOwnerID
To get selected owner id you can, for example, create a map Map<Integer,Integer> and store pairs ComboboxItemNumber -> OwnerId

Categories