How to get data to display when selecting items from a JComBox - java

I´m rather lost on how to get data to display in text fields when selecting something from a JComboBox. I got 2 tables in mysql which have a connection with a constraint of a foreign key (pelicula dirID and director dirID (pelicula and director are the tables)).
I got the directors names in a list so it can be displayed in the JComboBox from a mysql query but i don´t understand how i could get the text fields to change when choosing another director.
e.g
--- Titulo --- dur-genero-pais
--- Errementari 92 Horror Basque
String queryJOIN = "SELECT p.titulo, p.duracion, p.genero, p.pais, d.nombre, d.apellido"
+ " FROM filmoteca.pelicula p, filmoteca.director d"
+ " WHERE p.dirID = d.dirID";
List<String> comboBoxNames = new ArrayList<String>();
try {
Statement stmt = newBDD.con.createStatement();
ResultSet rs2 =stmt.executeQuery(queryJOIN);
while (rs2.next() ) {
String name = rs2.getString("nombre");
String lastname = rs2.getString("apellido");
comboBoxNames.add(name + " " + lastname);
}
newBDD.con.close();
}
catch (Exception exc) {
exc.printStackTrace();
}JComboBox comboBox = new JComboBox(comboBoxNames.toArray());
comboBox.setBounds(45,147,204,21);contentPane.add(comboBox);
When I add the columns with a setText it will appear but of course not change when i change the director in the combobox and that is where im having difficulties in finding a way to connect those two things so when one changes its value the other does as well.
e.g ´editorTitulo.setText(rs2.getString("titulo"));´
This is the GUI atm:

Related

Codename One SQL database storing wrong values

I am used to developing desktop applications with Java. Now I am trying Codename One to develop my first mobile app.
Trying to replicate my experiences with SQL databases I am running into a very odd storage behavior, which I cannot explain.
The database is created, but when I change the table input value, the new value gets ignored and just the old value is added. To save the new value, I have to delete the database.
I like the interface and any kind help would be appreciated.
Database db = Display.getInstance().openOrCreate("MyDB.db");
db.execute("CREATE TABLE IF NOT EXISTS Persons (Date NOT NULL,Event NOT NULL)");
String sql = "INSERT INTO Persons (DATE , Event) " + "VALUES ( 'John', '10000.00' );";
db.execute (sql);
// adds "John" to the database every time I click the button
// then I change the from "John" to "James"
// I am not adding the lines twice, just change the input
String sql = "INSERT INTO Persons (DATE , Event) " + "VALUES ( 'James', '10000.00' );";
db.execute (sql);
//keeps adding "John" to the database, even though value has been changed to "James"
Cursor cur = db.executeQuery("select * from Persons;");
Row currentRow= cur.getRow();
String dataText = currentRow.getString(0);
while (cur.next()) {
System.out.println(dataText);
}
You're not fetching the next row into dataText in your while() loop, so you're just repeatedly printing out the text from the first row.
It should be:
Cursor cur = db.executeQuery("select * from Persons;");
while (cur.next()) {
Row currentRow = cur.getRow();
String dataText = currentRow.getString("Date");
System.out.println(dataText);
}
If you examine the table with a separate query tool, like PhpMyAdmin, you should see that it contains both rows.
I hope I got the syntax right. I'm not a Java programmer and I got it from a tutorial.

Fetch all comma separated values as an unique element without affecting performance

Following is my data base table named feeds
column_name | data_type
-------------+-----------------------------
id | integer
category | text
question | text
answer | text
thumb | text
time | timestamp without time zone
The categories will be of comma separated values. I would like to get all comma separated values into an array that has got unique elements (No same categories will be present in the array).
To achieve this, I have created a separate table called category. When the user publishes a feed, i will populate both the feeds table and also category table at the same time as follows.
#POST
#Path("/post")
#Consumes(MediaType.APPLICATION_JSON)
public Response postStrMsg(String msg) {
String songString = "requesting";
JSONObject jsonObj = new JSONObject(msg);
try {
Connection connection = DbConnection.getConnection();
PreparedStatement stmt = connection.prepareStatement(
"INSERT INTO feeds ( CATEGORY , TOPIC , DESCRIPTION , THUMB , TIMEFRAME , AUTHOR ) VALUES( ?, ? , ? , ? , now() , ? )");
stmt.setString(1, jsonObj.getString("category"));
stmt.setString(2, jsonObj.getString("question"));
stmt.setString(3, jsonObj.getString("answer"));
stmt.setString(4, jsonObj.getString("thumb"));
stmt.setString(5, jsonObj.getString("author"));
stmt.executeUpdate();
String query = "INSERT INTO CATEGORY (SECTION) VALUES ('" + jsonObj.getString("category") + "');";
PreparedStatement stmts = connection.prepareStatement(query);
stmts.executeQuery();
songString = Utilities.constructJSON( "Posted Successfully",true);
} catch (Exception ex) {
songString = Utilities.constructJSON("Failure", false, ex.getMessage());
}
return Response.status(200).entity(songString).build();
}
And I used the following code to retrieve the categories when the user wants to know all categories. This will parse all comma separated values and filter all duplicate elements and it will provide the corresponding result.
Query :
"select min(c.id) as id, t.name from category c " + " cross join "
+ "unnest(string_to_array(c.category, ',')) AS t(name) " + "group by t.name order by 1";
Code
#GET
#Path("getCategories")
#Produces(MediaType.APPLICATION_JSON)
public String getCategories() {
ArrayList<Category> output = null;
try {
Connection connection = getConnection();
Statement stmt = connection.createStatement();
String query = "select min(c.id) as id, t.name from category c " + " cross join "
+ "unnest(string_to_array(c.category, ',')) AS t(name) " + "group by t.name order by 1";
ResultSet rs = stmt.executeQuery(query);
output = new ArrayList<Category>();
while (rs.next()) {
output.add(new Category(rs.getString("name")));
}
} catch (Exception ex) {
ex.printStackTrace();
}
JSONArray jsArray = new JSONArray(output);
return jsArray.toString();
}
The issue is that,
Since two different tables are populated at the same time, the performance is being degraded. Is it possible to achieve the same functionality without creating the same table?
No results were returned by the query while posting the feed
I think you need two more tables. One for categories and the other one to combine categories with feed. You should create a category table as follows:
column_name | data_type
-------------+-----------------------------
id | integer
category | text
And feedCategory table as follows:
column_name | data_type
-------------+-----------------------------
id | integer
category_id | integer
feed_id | integer
One feed can have more than one category. So you can populate the last table based on that.
It is not the best way to parse category text each time you will retrieve from database. How about querying feeds by category? Are you gonna parse category column for each feed and see if you have it in there?

Set the selected Jtree Node to JTable

The function need to be accomplished is:
Select main group
Select from sub-group (TEST NAME)
Click >> button which means move the selection to Jtable
Show the slected (Test) with corresponding price on Jtable
conditions:
if the selected node (test name) alread has been selected and added to the Jtable show message say: Test name already added.
we can select and add many test name
Demo image
impotant to say that JTree data come from two tables main-group and sub-group
Here the code: of >> button
try {
DefaultMutableTreeNode selectedElement = (DefaultMutableTreeNode) TestTree.getSelectionPath().getLastPathComponent();
Object[] row = {selectedElement};
DefaultTableModel model = (DefaultTableModel) myTests_table.getModel();
System.out.println(String.valueOf(row).toString() + "Hi");
if (selectedElement.isLeaf() == true) {
//model.addRow(row);
// retrive date from DB price
String sql = "SELECT sub_group.name AS 'name', sub_group.price AS 'price'"
+ "FROM sub_group \n"
+ "where sub_group.name = '" + row + "' ";
pst = conn.prepareStatement(sql);
rs = pst.executeQuery(sql);
while (rs.next()) {
myTests_table.setModel(DbUtils.resultSetToTableModel(rs));
}
} else {
JOptionPane.showMessageDialog(null, "Please Choose Test name!", "Error", JOptionPane.WARNING_MESSAGE);
}
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "Error");
}
Dears
where is the error?
Thanks
Add a TreeSelectionListener to your JTree, as shown here. In the listener, update the TableModel of your JTable; the listening table will update itself accordingly, when your implementation of setValueAt() fires the relent TableModelEvent. Your table model should extend AbstractTableModel, as shown here, and contain a Set<Row>. Your Row class should hold the name and price. If Row implements Comparable<Row>, as shown in the example cited here, then Set<Row> will automatically exclude duplicates when you invoke add().
if the issue is that the new TableModel is not being reflected in the UI, use tableModel.fireTableDataChanged().

confusion over using values in Java within SQL statements

I need to retrieve a list of vehicle registrations from an SQL database and put them into a dropdown list in the java GUI. Once a Vehicle Registration is selected (as part of a login sequence) from the list I want to use this in the "where" statement of subsequent SQL queries made to the database to get things like inventory statuses etc that are only for that vehicle.
I have done the first part i.e. retrieved the list from the database and displayed the veh regs in the dropdown for the user to select, I have managed to display this in an optional panel as well as display it in another class in a Jlabel box but I cannot seem to figure out how to use this selected veh reg in a seperate query class i.e as part of a select/where statement?
I have been trying to find a solution to this but am getting confused on whether to use an array list and put the registration number into this and then how to make this available to other classes so I can retrieve the value to use in the SQL statement. I am quite lost now so any advice in the right direction will be very helpful.
I am very new to Java and programming altogether so if you feel the need to make sarcastic (you are such a noob) type comments then don't bother posting!
This is the code that grabs the registrations from the database and adds them to the combo box in one GUI:
private void populateRegistration() {
try {
// create a connection to database
pst = conn.prepareStatement("SELECT VehicleRegistrationNumber FROM vehicle;");
// create a query to get vehicle regs
rs = pst.executeQuery();
// add vehicle regs to combobox
while (rs.next()) {
jComboBox1.addItem(rs.getString("VehicleRegistrationNumber"));
}
} catch (SQLException ex) {
Logger.getLogger(Login_GUI.class.getName()).log(Level.SEVERE, null, ex);
}
This is the code In another GUI Class that shows this vehicle registration in a dialogue box and then shows it in a text field in the GUI:
public ArrayList<String> getTableContent()
{
DatabaseConnection db = new DatabaseConnection();
try {
//Sql Return Statement
String newQuery= "SELECT P.PatientFirstName, P.PatientLastName, P.PatientHouseNumber, P.PatientStreetName, P.PatientPostcode, P.PatientBreathing, P.ProblemInformation, C.AMPDSCategory, \n" +
"I.NumberHurt,T.TaskClosed, H.HospitalSpaceAvailable, H.HospitalName, H.HospitalPostcode, V.VehicleRegistrationNumber, EM.DateTimeReported\n" +
"FROM Patient AS P\n" +
"JOIN Category AS C\n" +
"ON C.Category_ID = P.CategoryID\n" +
"--AND P.Patient_ID = 2\n" +
"JOIN Incident AS I\n" +
"ON I.Incident_ID = P.IncidentID\n" +
"JOIN TASK AS T\n" +
"ON T.IncidentID = I.Incident_ID\n" +
"JOIN Hospital AS H\n" +
"ON H.Hospital_ID = T.HospitalID\n" +
"JOIN Vehicle AS V\n" +
"ON T.Task_ID = V.TaskID\n" +
"JOIN ECCPersonnel AS EC\n" +
"ON I.ECCPersonnelID = EC.ECCPersonnel_ID\n" +
"JOIN EmergencyCall AS EM\n" +
"ON EC.CallID = EM.Call_ID\n" +
"WHERE T.Task_ID=1" +
"--WHERE V.VehicleRegistrationNumber = '?'";
I know the SQL is ugly but it works so I will refine it later if I get time. I believe I need to define the ? but have no idea how to reference the ? to the vehReg value!!
First you should allways close what you have opened. So in populateRegistration() do not forget rs.close() and pst.close().
Next to reference the ? to the vehReg, you create a PreparedStatement and call its setString method (supposing vehReg is a String).
pst = conn.prepareStatement(newQuery);
pst.setString(1, vehReg);
rs = pst.executeQuery();
(try, catch, declarations, and actual read ommitted for brevity)
Remember that columns are numbered starting by 1.

Retrieve database in java using JTextField to search

So, i would like to retrieve database information where a user will search certain columns using text fields, like this:
column1 find userinput,
column2 find userinput,
column3 find userinput,
The problem im having is the sql statement:
String sql = "select * from table where column = '" + textfield1.getText() + "'";
If textfield1 is empty, it will only retrieve entries that contain nothing.
What im trying to retrieve will have 6 text field, meaning 6 columns in the database. Using java i would need alot of if statements.
Is there any other way to shorten this?
EDIT
-- MORE INFO --
The if statements will start from:
if (!(t1.getText().equals("")) && !(t2.getText().equals("")) && !(t3.getText().equals(""))
&& !(t4.getText().equals("")) && !(t5.getText().equals("")) && (t6.getText().equals("")))
all the way down to
if (t1.getText().equals("") && t2.getText().equals("") && t3.getText().equals("")
&& t4.getText().equals("") && t5.getText().equals("") && t6.getText().equals("")
covering all possible combinations of the 6 input fields, the point of all these statements is to ignore empty text fields but provide the corresponding sql statement.
I don't know how to calculate the possible combinations other than writing them all down(i started, there was too many).
I didn't really understand why those ifs, you should elaborate more your question but i will try to help as i can.
Well, if you want to retrieve everything from the database you could use LIKE:
String sql = "select * from table where column like '%" + textfield1.getText() + "%'";
This way you'll get everything with the containing text, it means, if the field is empty it will bring all results, i guess this is the best way to do, to avoid unnecessa if clauses.
Another thing, to check for empty fields you should use:
t1.getText().trim().isEmpty()
BUT if you let they write white spaces the LIKE won't help you then you need to .trim() all your texts then your white spaces will be ignored.
The following can be formulated much neater, but to make the point:
JTextField ts = new JTextField[6];
Set<String> values = new HashSet<>(); // Removes duplicates too.
for (JTextField t : ts) {
String text = ts.getText().trim();
if (!text.isEmpty()) {
values.add(text);
}
}
// Build the WHERE condition of a PreparedStatement
String condition = "";
for (String value : values) {
condition += condition.isEmpty() ? "WHERE" : " OR";
condition += " column = ?";
}
String sql = "select * from table " + condition;
PreparedStatement stm = connection.prepareStatement(sql);
int index = 1; // SQL counts from 1
for (String value : values) {
stm.setString(index, value);
++index;
}
ResultSet rs = stm.executeQuery();
The usage of a PreparedStatement makes escaping ' (and backslash and such) no longer needed and also prevents SQL injection (see wikipedia).
i have a problem i want to search data based on multiple jtext fields where did i go wrong coz this displays only one row which has the first id
private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
String sql="SELECT Employee.EmpID,Employee.Fname,Employee.Mname,Employee.Sname,Employee.DoB,Employee.Phone,"
+ "Employee.Email,Employee.Nationality,Employee.Desegnition,Employee.NSSF,Employee.WCF,"
+ "Employee.BSalary,Allowance.medical,Allowance.Bonus,Allowance.others,Allowance.tov,Allowance.TA,"
+ "Attendece.Hrs from Employee,Allowance,Attendece WHERE "
+ "Employee.EmpID=Allowance.EmpID and Attendece.EmpID=Allowance.EmpID AND Employee.EmpID=? AND Attendece.Dt=?";
try{
pd=conn.prepareStatement(sql);
pd.setString(1,id.getText());
pd.setString(2,Date1.getText());
r=pd.executeQuery();
//setting the text fields
if(r.next())
{
String a=r.getString("EmpID");
eid.setText(a);
String b=r.getString("Fname");
fname.setText(b);
String c=r.getString("Mname");
mname.setText(c);
String d=r.getString("Sname");
sname.setText(d);
String e=r.getString("DoB");
dob.setText(e);
String f=r.getString("Desegnition");
Des.setText(f);
String g=r.getString("Bsalary");
bsal.setText(g);
String h=r.getString("Phone");
phone.setText(h);
String i=r.getString("Email");
email.setText(i);
String j=r.getString("Nationality");
nationality.setText(j);
String k=r.getString("Desegnition");
Des.setText(k);
String l=r.getString("NSSf");
nssf.setText(l);
String m=r.getString("WCF");
wcf.setText(m);
String n=r.getString("tov");
oh.setText(n);
String o=r.getString("Bonus");
bn.setText(o);
String p=r.getString("medical");
md.setText(p);
String q=r.getString("others");
ot.setText(q);
String s=r.getString("TA");
ta.setText(s);
String t=r.getString("Hrs");
hrs.setText(t);
int day;
day=Integer.parseInt(t)/8;
days.setText(Integer.toString(day));
double week=day/7;
weeks.setText(Double.toString(week));
}
r.close();
pd.close();
}catch(Exception e)
{
}

Categories