Adding distinct data to jComboBox from database - java

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

Related

Create new table in SQLite with query result

I have this code in Java and i need to insert the result into new table. Is this possible with just editing this query?
ResultSet result = stat.executeQuery("SELECT artist, COUNT(artist) AS countartist FROM table1 GROUP BY artist ORDER BY countartist DESC;");
Try this:
ResultSet result = stat.executeUpdate("CREATE TABLE newtable AS SELECT artist, COUNT(artist) AS countartist FROM table1 GROUP BY artist ORDER BY countartist DESC");

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

How to fetch MySQL data without creating Object from Class in 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.

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

problem in setString method.in retrieving data from the table

i have two tables "Table1" with columns user_name,Password and course ID and another table "course" with columns course_id,course_name.I have used the following code to display the course ID from Table1 according to the user_name received from the login page.using ResultSet rs1.now i want to retrieve the course_name from the table "course" according to the course ID receieve from "Table1".for that in the second query pstmt2.setString(1, ); what parameter i should use to get the course_id value from the previous query
HttpSession sess=request.getSession();
String a=(String)sess.getAttribute("user");
String b=(String)sess.getAttribute("pass");
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con=DriverManager.getConnection("jdbc:odbc:ggg");
Statement st = con.createStatement();
String query="select * from Table1 where user_name=?";
PreparedStatement pstmt=con.prepareStatement(query);
pstmt.setString(1,a);
ResultSet rs1=pstmt.executeQuery();
while(rs1.next())
out.println("<h3>COURSE ID: "+rs1.getString("course ID")+"<h3>");
String query2="SELECT * from course where course_id=?";
PreparedStatement pstmt2=con.prepareStatement(query2);
pstmt2.setString(1,);
ResultSet rs2=pstmt2.executeQuery();
while(rs2.next())
{
out.println("<h3>course name: "+rs2.getString("course_name")+"<h3>");
}
why do you go for two turns of database hit, even though you created one time connection object.
modify the query as below
SELECT * from course where course_id = (select course_id from Table1 where user_name=?);
from this query you noneed to give input of courseid also.
No need to hit database twice to get the results that you need. use the query
Select table1.course_id, course.course_name from table1, course where table1.course_id=course_id and table1.user_name=?
This should set the course_id parameter:
pstmt2.setString(1,rs1.getString("course_id"));
Or, as I see the "course_id" column may have a different name in "Table1":
pstmt2.setString(1,rs1.getString("course ID"));
As the other post mentioned there's no need to go to another set of query. Try this example query:
SELECT course.course_id, course.course_name
FROM table1 t1
INNER JOIN course c
ON t1.course_id = c.course_id
WHERE t1.user_name = ?;
Now if you insist your coding the parameter o your pstmt2.setString(1,); is:
pstmt2.setString(1,rs1.getString("course_id")); //or course ID defending on your column name

Categories