Java cast to object changing other object - java

for (int i = 0; i < info.size(); i++) {
User b = (User) info.get(i);
rs = stmt.executeQuery("Select ARTIST,TITLE from SONGS WHERE ID = (SELECT ID from USERS WHERE USERNAME = " + "'" + b.Username + "'" + ")");
while (rs.next()) {
String artist = rs.getString("ARTIST");
String title = rs.getString("TITLE");
b.Songs.add(artist + "-" + title);
}
System.out.println(b.getSongs());
}
so this is my code which contains an array of users (info array) each of which have an array called songs which stores each song they own. I want to select the users songs form the song DB using their username which works fine, then add it to that users array.
However when I run the code this happens:
The info array has 2 users in it.
I get the first user 'Tim'
Get the songs he has: "Queen - We will rock you" and add it to his array, works fine.
Then loop and the next user is selected, but when I add to his array it contains the Queen song, then his songs.
I'm not sure how they are being added to the 2nd users songs array, the SQL works fine and only selects that users songs, but some how b.songs from the previous user is passed into the next user?

Could you be joining on the wrong column?
Select ...from SONGS WHERE ID = (SELECT ID from USERS where ...)
Seems wrong, that SONGS.ID is the ID of the user.
Shouldn't it be
Select ...from SONGS WHERE USER_ID = (SELECT ID from USERS where ...)
?
Also, die to the way you construct the query string, note that your code will fail if username contains the ' character.
Moreover, it's vulnerable to SQL Injection - a serious security threat.

Related

How can I search new inserts in my access database?

I created an AddressBook GUI application with Insert, Update, Delete, Search, and Print functions. It connects to my access database table which contains four tables(names, addresses, phoneNumbers, and emailAddresses)
So far everything is working except when I try to search new input I just inserted into the table. If I search records I placed directly into access it works.
I THINK I narrowed down the problem but don't know how to fix it. When I insert new records into my table the names table creates a new primary key for that record but the rest of the tables don't, they only create a new foreign key number. Since my search is based on inner joining the id's I'm guessing my problem lies here but I'm not sure.
Here Is my Search Code
if (e.getActionCommand().equals("Search")){
JFrame mini = new JFrame();
// Gets user input. If user presses Cancel, 'name' will be null
String first = JOptionPane.showInputDialog(mini,"Enter first name:");
String last = JOptionPane.showInputDialog(mini, "Enter last name:");
try{
resultSet = statement.executeQuery( "SELECT * FROM ((names INNER JOIN addresses
ON names.personID = addresses.addressID)INNER JOIN phoneNumbers
ON names.personID = phoneNumbers.phoneID) INNER JOIN emailAddresses
ON names.personID = emailAddresses.emailID
WHERE lastName LIKE '%" + last + "%' AND firstName LIKE '%" + first+"%'");
resultSet.next();
jTextField1.setText(resultSet.getString("firstName"));
jTextField2.setText(resultSet.getString("lastName"));
jTextField3.setText(resultSet.getString("address1"));
jTextField4.setText(resultSet.getString("address2"));
jTextField5.setText(resultSet.getString("city"));
jTextField6.setText(resultSet.getString("state"));
jTextField7.setText(resultSet.getString("zipcode"));
jTextField8.setText(resultSet.getString("phoneNumber"));
jTextField9.setText(resultSet.getString("emailAddress"));
jTextField10.setText(resultSet.getString("personID"));
jTextField10.setEditable(false);
} catch(SQLException sqlException) {
JOptionPane.showMessageDialog(null, sqlException.getMessage(), "Error",
JOptionPane.ERROR_MESSAGE);
}
}
Access uses * as the wildcard character, not %

Want to Parse raw string coming from Java UI upon user selection to SQL query String?

I am wondering how can I parse raw string coming from webapp Java UI upon user selection to SQL query String in Java !
For Example : On UI, I have 100 companies (and also a database having info about these companies) and if suppose user selected two companies from UI and clicked search button then It should return all information about these two companies comp1 and comp2 and relationships among these two companies and fetch following query from sql database :
The table CompanyData contains all general information about companies like ID, Name, CEO, Stablishment year, Awards won, global ranks, etc....
Table ComapanyDomain contains information about the domains, technologies and expertise of companies,
SELECT * FROM CompanyData
WHERE ID IN (SELECT ID FROM CompnayDomain
WHERE companyName = "comp1"
and ID IN ( SELECT ID FROM CompnayDomain
WHERE companyName = "comp2"))
the string to be parsed It would look like " Company comp1 and comp2 " in above scenario
Thank you
I would approach it like this (I didn't use your sql query because it didn't make any sense at all, it would return always an empty set unless 2 companies have the same ID)
String input = "Company comp1 and comp2";
String data = input.substring(8, input.length());
String [] companies = data.split("\\b and \\b");
String sql = "SELECT * FROM CompanyData WHERE ID IN (SELECT ID FROM CompanyDomain WHERE companyName IN (";
for(int i = 0; i < companies.length - 1; i++) {
sql += "?,"
}
sql += "?)";
for(int i = 0; i < companies.length; i++) {
// Use prepared statement and insert the values here
}

Mysql JDBC - not entering ResultSet + incorrect no. of rows

I came across a problem with going through a ResultSet I'm generating from my MySQL db. My query should return at most one row per table (I'm looping through several tables searching by employee number). I've entered data in some of the tables; but my test o/p says that the resultset contains 0 rows and doesn't go through the ResultSet at all. The o/p line it's supposed to print never appears. It was in a while loop before I realised that it'd be returning at most one row, at which point I just swapped the while(rs.next()) for an if(rs.first()). Still no luck. Any suggestions?
My code looks like this:
try
{
rsTablesList = stmt.executeQuery("show tables;");
while(rsTablesList.next())
{
String tableName = rsTablesList.getString(1);
//checking if that table is a non-event table; loop is skipped in such a case
if(tableName.equalsIgnoreCase("emp"))
{
System.out.println("NOT IN EMP");
continue;
}
System.out.println("i'm in " + tableName); //tells us which table we're in
int checkEmpno = Integer.parseInt(empNoLbl.getText()); //search key
Statement s = con.createStatement();
query = "select 'eventname','lastrenewaldate', 'expdate' from " + tableName + " where 'empno'=" + checkEmpno + ";"; // eventname,
System.out.println("query is \n\t" + query + "");
rsEventDetails = s.executeQuery(query) ;
System.out.println("query executed\n");
//next two lines for the number of rows
rsEventDetails.last();
System.out.println("no. of rows is " + rsEventDetails.getRow()+ "\n\n");
if(rsEventDetails.first())
{
System.out.println("inside the if");
// i will add the row now
System.out.println("i will add the row now");
// cdTableModel.addRow(new Object[] {evtname,lastRenewalDate,expiryDate});
}
}
}
My output looks like this:
I'm in crm
query is
select 'eventname','lastrenewaldate', 'expdate' from crm where 'empno'=17;
query executed
no. of rows is 0
I'm in dgr
query is
select 'eventname','lastrenewaldate', 'expdate' from dgr where 'empno'=17;
query executed
no. of rows is 0
NOT IN EMP
I'm in eng_prof
query is
select 'eventname','lastrenewaldate', 'expdate' from eng_prof where 'empno'=17;
query executed
no. of rows is 0
I'm in frtol
query is
select 'eventname','lastrenewaldate', 'expdate' from frtol where 'empno'=17;
query executed
no. of rows is 0
(and so on, upto 17 tables.)
The '17' in the query is the empno that I've pulled from the user.
The thing is that I've already entered data in the first two tables, crm and dgr. The same query in the command line interface works; this morning, I tried the program out and it returned data for the one table that had data in it (crm). The next time onwards, nothing.
Context: I'm working on a school project to create some software for my dad's office, it'll help them organise the training etc schedules for the employees. (a little like Google Calendar I guess.) I'm using Netbeans and Mysql on Linux Mint. There are about 17 tables in the database. The user selects an employee name and the program searches for all entries in the database that correspond to an 'event' (my generic name for a test/training/other required event) and puts them into a JTable.
The single quotes around the column names and table name in the creation of the query seem to have caused the problem. On changing them to backticks, retrieval works fine and the data comes in as expected.
Thank you, #juergend (especially for the nice explanation) and #nailgun!

(JAVA/SQL) ResultSet only retrieving one row from MySQL when it should retrieve more

I'm having a little trouble retrieving data from a MySQL database in my Java servlet. For reference, my web app is constructed like a library - you can check out items, and check them back in.
When you first click "check out", your request gets sent to an admin, let's call that person a librarian, who must approve or disapprove your request. Let's say I login, pick some items, and hit "checkout". Here's what happens:
The items get added to my "cart"
In the master list of items on the database, each item has a VARCHAR called STATUS, which identifies whether or not that item is "In Stock". For each item I chose, that variable gets changed to a unique identifier associated with my user account.
My request gets added to a table called requests_list
Approval, generic check-in, and so on work fine. What doesn't work so well is clicking "disapprove". Here's what should happen:
The request gets removed from requests_list
The requestor's "cart" of items gets truncated
The items themselves get declared "In Stock"
Here's what's been happening:
The request gets removed from requests_list
The requestor's "cart" of items gets truncated
Only the first item in the cart gets checked back in
Here's the code I'm working with so far:
stmt.execute("DELETE FROM requests_list WHERE UNIQUE_ID = '"
+ selected_ID + "'"); // this seems to work
stmt.execute("TRUNCATE TABLE checkout_" + selected_ID); // also seems to work
ResultSet all_gear = stmt
.executeQuery("SELECT * FROM gear_master_list");
while (all_gear.next()) {
if (all_gear.getString(5).equals(selected_ID)) {
stmt.execute("UPDATE gear_master_list SET STATUS = 'In Stock' WHERE ID_NUM = "
+ all_gear.getInt(6));
}
}
all_gear.close();
Some notes, to explain a few of the variables:
selected_ID - The librarian clicks a drop-down menu to access the list of users who have made requests. After he or she chooses one, that user's unique identifier becomes selected_ID
checkout_selected_ID - Your "cart" is a table in the database. This table is named after your unique ID, so if my unique ID were bunnies, my table would be checkout_bunnies
stmt and the Connection it draws its Statement from are all valid and working
gear_master_list is the table with all the gear, all_gear.getInt(6) references the unique inventory number that each piece of gear has, and all_gear.getString(5) is the STATUS variable I mentioned
I have tried doing this differently, such that the code runs through all the items in the cart, updates the status, then truncates the table. That didn't work either - it was still finicky about updating the status, and the table wouldn't truncate.
TL;DR: My ResultSet is only getting me one row from my table (I think), even though I'm using a while loop and there's more than one row. What's going on? Is there a better, more efficient way to do this?
This may be a concurrent modification issue - your first query holds open a cursor on the database, and while looping over that cursor you're performing updates on that same data, all within the same transaction.
Could you try this?
stmt.execute("DELETE FROM requests_list WHERE UNIQUE_ID = '"
+ selected_ID + "'"); // this seems to work
stmt.execute("TRUNCATE TABLE checkout_" + selected_ID); // also seems to
// work
ResultSet all_gear = stmt
.executeQuery("SELECT * FROM gear_master_list");
List<String> gear_items = new ArrayList<>();
while (all_gear.next()) {
gear_items.add(all_gear.getString(5));
}
all_gear.close();
for (String gear_item: gear_items){
if (all_gear.getString(5).equals(selected_ID)) {
stmt.execute("UPDATE gear_master_list SET STATUS = 'In Stock' WHERE ID_NUM = "
+ all_gear.getInt(6));
}
}
stmt.close();
Many thanks to hugh for his great help with this question - his answer is correct. I just had to make a couple modifications to help his response fit my code.
In case anyone else is having this issue, hugh was right that this is a concurrent modification problem. However, there was one slight typo in his response (the ResultSet gets closed before certain statements are called), so I figured I would post my modified code just in case it proved helpful to anyone:
stmt.execute("DELETE FROM requests_list WHERE UNIQUE_ID = '" + selected_ID + "'"); // this seems to work
stmt.execute("TRUNCATE TABLE checkout_" + selected_ID); // also seems to work
ResultSet all_gear = stmt.executeQuery("SELECT * FROM gear_master_list");
ArrayList<Object[]> gear_items = new ArrayList<Object[]>();
while (all_gear.next()) {
Object[] added = new Object[2];
added[0] = all_gear.getString(5);
added[1] = all_gear.getInt(6);
gear_items.add(added);
}
all_gear.close();
for (Object[] gear_item : gear_items) {
if (gear_item[0].equals(selected_ID)) {
stmt.execute("UPDATE gear_master_list SET STATUS = 'In Stock' WHERE ID_NUM = " + gear_item[1]);
}
}
stmt.close();
// thanks again to hugh!

sql query to retrieve sum of contact records that match to one user with mysql and java

I have two table user and contact, each user can have multiple contacts
I want to draw a graph (camembert) with JFreeChart(java library) to present the number of contacts that has each user
I tested :
select u.name, sum(c) from user u, contact c
but I have
unknown column c in field list
here are the structures of tables :
utilisateur = idutilisateur, identifiant, motdepasse, nom, prenom
contact = idcontact, ............, idutilisateur
How can I achieve that,
and also, please give me links to tutorials for learning to make queries like that because always I have this problem and I find only basic tutorials
thank you in advance
You need to reference the column of the table that you're trying to count, not just the table itself.
if you try:
select u.name, count(c.ID)
from user u, contact c
You can count all records that have a value in the ID field. If this is a primary key, then all records should have this field. Note the change from sum to count.
This won't fully solve your problem. You also have to let sql know that the two tables are related by joining:
JOIN contact
ON user.ID=contact.userID
Put this after the from user u instead of , contact c
For a good start to learning sql, try here: http://www.w3schools.com/sql/default.asp
String sql1 = "SELECT u.nom, COUNT(c.idcontact) ContactsCount FROM utilisateur u LEFT " + "JOIN contact c ON u.idutilisateur = c.idutilisateur " + "GROUP BY u.nom";
sql = "SELECT u.nom + ' ' + u.prenom dd, COUNT(c.idcontact) FROM utilisateur u " + "LEFT OUTER JOIN contact c ON u.idutilisateur = c.idutilisateur GROUP BY u.nom + ' ' + u.prenom";

Categories

Resources