Datechooser for SQL query - java

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

Related

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 get value from reference table based on foreign key?

I have two tables with the foreign key relating them:
enter image description here
I have used a SQL query to retrieve the value form both tables:
User u = new User();
String sql = "SELECT * FROM user INNER JOIN account ON user.id = account.user WHERE user.id = 1 ";
try {
Statement stm = con.createStatement();
ResultSet rsu = stm.executeQuery(sql);
while(rsu.next()){
u.setFname(rsu.getString("fname"));
u.setLname(rsu.getString("lname"));
u.setMname(rsu.getString("mname"));
u.setGender(rsu.getString("gender"));
u.setAddress(rsu.getString("address"));
u.setCitizenship(rsu.getLong("citizenship"));
/**
*
* Here i want to get values of account table and set it on
* user object to return u
*
*/
}
return u;
} catch (SQLException e) {
e.printStackTrace();
}
It is easy to get the values of table. All you need to do is provide the column name of account table which you already got in your ResultSet.
u.setAccountID(rsu.getLong("accId"));
Here account id is stored in Result set object which you already retrieved from database in result set
1) Include account data in your SQL like so:
SELECT user.*, account.* FROM user INNER JOIN account ON user.id = account.user WHERE user.id = 1
2) Access account field just like user fields:
u.setAccountType(rsu.getString("accountType"));
u.setAccountNo(rsu.getString("accountNo"));
3) Make sure to close Statement in finally block.
4) You dont need to iterate the whole result set since you are expecting only one record. Just replace while with if.

Setting values in a table from another table

What would be the correct way to write this query?
String squery= "update Room set GuestCode="+gc+", FirstName=(select FirstName from GuestDetails where GuestCode="+gc+"), LastName=(select LastName from GuestDetails where GuestCode="+gc+"), Country=(select Country from GuestDetails where GuestCode="+gc+"), State=(select State from GuestDetails where GuestCode="+gc+"), City=(select City from GuestDetails where GuestCode="+gc+"), ContactNo=(select ContactNo from GuestDetails where GuestCode="+gc+") where RoomNo="+rn+"";
i am trying to set some values in a table(Room) from another table(GuestDetails) with guestcode as input. I am getting an exception as invalid memo, ole, or hyperlink object in subquery. Please help.
This may be a Better way of writing your update. This works in sql server
UPDATE A
SET GuestCode = 'gc',
FirstName = B.FirstName,
LastName = B.LastName,
Country = Country,
State = B.State,
City = B.City,
ContactNo = B.contactNO
FROM ROOM A
JOIN GuestDetails B
ON b.GuestCode = 'gc'
WHERE RoomNo = 'rn';
Its better to use a stored procedure to avoid sql injection. Your code is vers vulnerable for injection.
Also use a join to avoid sub-selects due to performance issues.

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.

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