This question already has answers here:
Dynamic JComboBoxes
(2 answers)
Closed 6 years ago.
Greating from Belgium.
I am now 3 days trying to populate between values with combobox.
I use Sqlite and using 4 tables to save the data in table "Recipes"
So if i choose lets say "meat" from cmbCategory, from table "sbCategory", the other combobox "cmbDescription" from table "Products" should only show what is relevant with the category "meat"
The code shown is working I can get values to the boxes. and this i pasted at the bottom "fillCombo();"
I am really desperate. 3 days searching to let this work, until i found this site. I hope you guys can help me out here. I admire the knowledge you guys have. I am a chef who is trying to write his own application.
Thank you in advance. I can not pay you guys, but if you re in Belgium i can offer some coffee..
//
public void fillCombo(){
try {
String sql= "Select * from sbCategorie";
String sql1= "Select * from Products";
String sql2= "Select * from UnitsRecipe";
String sql3= "Select * from Classification";
PreparedStatement pst=connection.prepareStatement(sql);
PreparedStatement pst1=connection.prepareStatement(sql1);
PreparedStatement pst2=connection.prepareStatement(sql2);
PreparedStatement pst3=connection.prepareStatement(sql3);
ResultSet rs=pst.executeQuery();
ResultSet rs1=pst1.executeQuery();
ResultSet rs2=pst2.executeQuery();
ResultSet rs3=pst3.executeQuery();
while(rs.next()){
BoxCategory.addItem(rs.getString("Categorie"));
//BoxDescription.addItem(rs.getString("Description"));
}
while(rs1.next()){
BoxDescription.addItem(rs1.getString("Description"));
}
while(rs2.next()){
BoxUnit
.addItem(rs2.getString("Unit"));
}
while(rs3.next()){
BoxClassification
.addItem(rs3.getString("Classification"));
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
this is as shown
BoxCategory.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent arg0) {
//
//
String s=BoxCategory.getSelectedItem().toString();
String sql="Select * from Products where Category='"+s+"'";
//
try {
PreparedStatement pst=connection.prepareStatement(sql);
ResultSet rs=pst.executeQuery();
while (rs.next()){
//BoxDescription.removeAllItems();
BoxCategory.setSelectedItem(rs.getString("Description"));
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Could you please replace the following snippet of code:
BoxCategory.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent arg0) {
//
//
String s = BoxCategory.getSelectedItem().toString();
String sql = "Select * from Products where Category='" + s + "'";
//
try {
PreparedStatement pst = connection.prepareStatement(sql);
ResultSet rs = pst.executeQuery();
while (rs.next()) {
// BoxDescription.removeAllItems();
BoxCategory.setSelectedItem(rs.getString("Description"));
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
by the following snippet:
BoxCategory.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent arg0) {
String s = BoxCategory.getSelectedItem().toString();
String sql = "Select * from Products where Category='" + s + "'";
try {
PreparedStatement pst = connection.prepareStatement(sql);
ResultSet rs = pst.executeQuery();
BoxDescription.removeAllItems();
while (rs.next()) {
BoxDescription.addItem(rs.getString("Description"));
}
} catch (SQLException e) {
e.printStackTrace();
}
}
});
and see the results?
Related
This is a method to add a new planet to an observablelist of customers.
I am wondering if I am using the try with resources correctly and if the auto-close is working.
public static Customer addPlanet(Customer customer) {
String query1 = "Select * from planet where planet=? AND universeID=?";
String query2 = "INSERT INTO planet (planet,universeID) VALUES(?,?)";
try (PreparedStatement statement = (PreparedStatement) Database.connection.prepareStatement(query1);
PreparedStatement statement2 = (PreparedStatement) Database.connection.prepareStatement(query2)) {
statement.setString(1, customer.getPlanet());
statement.setString(2, Integer.toString(customer.getUniverseID()));
try (ResultSet rs = statement.executeQuery()) {
if (rs.next()) {
int planetId = rs.getInt(1);
customer.setPlanetID(planetId);
return customer;
} else {
statement2.setString(1, customer.getPlanet());
statement2.setInt(2, customer.getUniverseID());
statement2.executeUpdate();
return addPlanet(customer);
}
} catch (SQLException e) {
e.printStackTrace();
return null;
}
} catch (SQLException e) {
e.printStackTrace();
}
return customer;
}
My question is, does this part need to be enclosed in a try-catch block or does it get closed automatically.
statement2.executeUpdate();
It gets closed. Anything in the try gets closed at the end if they are AutoCloseable.
Hi I want to bring results from a table using SQL query but I am getting the message SQLServerResultSet3 as a result.
I take as an example the below code but it isn't working for me, any idea what I did wrong cause I am new to this ty!
searching from database and showing the output
private void searchquantity(){
//ArrayList <Update_del_insert_products> proList =new ArrayList <Update_del_insert_products> ();
Connection connection =getConnection();
String query ="SELECT * FROM Products WHERE Pro_Quantity <=20";
Statement sts=null;
ResultSet rsr=null;
try{
sts = connection.createStatement();
rsr = sts.executeQuery(query);
//Update_del_insert_products update_del_insert_products ;
if(rsr.next()) {
JOptionPane.showMessageDialog(null,rsr);
}else{
JOptionPane.showMessageDialog(null, "Not Found");
}
}catch (Exception e) { JOptionPane.showMessageDialog(null, e); }
}
=================================================================
private void Check_CapacityActionPerformed(java.awt.event.ActionEvent evt) {
searchquantity();
}
check rows for products that are below 20 in quantity table
private void searchquantity(){
Connection connection =getConnection();
String query ="SELECT * FROM Products WHERE Pro_Quantity <=20";
Statement sts=null;
ResultSet rsr=null;
int a=0;
try{
sts = connection.createStatement();
rsr = sts.executeQuery(query);
while(rsr.next()) {
JOptionPane.showMessageDialog(null,rsr.getString("Pro_Id"));
JOptionPane.showMessageDialog(null,rsr.getString("Pro_Name"));
a=1;
}
if (a==0){
JOptionPane.showMessageDialog(null, "Not Found");
a=0;}
}catch (Exception e) { JOptionPane.showMessageDialog(null, e); }
}
I have a jComboBox that getting data from MySQL server database.
When I add new data to database, the jComboBox doesn't show it, and I must reopen my program to add the new data to jComboBox.
How can I refresh jComboBox data automatically?
This is my code :
private void dataComboBox(){
try {
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/shop","root","");
Statement stat = con.createStatement();
String sql = "select id from perfume order by id asc";
ResultSet res = stat.executeQuery(sql);
while(res.next()){
Object[] ob = new Object[3];
ob[0] = res.getString(1);
jComboBox5.addItem(ob[0]);
}
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e);
}
}
private void showCBdata(){
try {
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/shop","root","");
Statement stat = con.createStatement();
String sql = "select name from perfume where id='"+jComboBox5.getSelectedItem()+"'";
ResultSet res = stat.executeQuery(sql);
while(res.next()){
Object[] ob = new Object[3];
ob[0]= res.getString(1);
jTextField8.setText((String) ob[0]);
}
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e);
}
}
//call method
private void jComboBox5ActionPerformed(java.awt.event.ActionEvent evt) {
showCBdata();
}
can you help me?
thank you..
You can do it in this way it will automatically refresh the combobox
try {
comboBox.removeAllItems();
sql = "SELECT * FROM `table_name`";
rs = stmnt.executeQuery(sql);
while (rs.next()) {
String val = rs.getString("column_name");
comboBox.addItem(val);
}
} catch (SQLException ex) {
Logger.getLogger(DefineCustomer.class.getName()).log(Level.SEVERE, null, ex);
}
removeAllItems(); method will clean the combobox to insure that not to repeat values.
You do not need to create a separate Object to add in jComboBox instead you can add String too.
Inzimam Tariq IT's Code (above):
try {
comboBox.removeAllItems();
sql = "SELECT * FROM `table_name`";
rs = stmnt.executeQuery(sql);
while (rs.next()) {
String val = rs.getString("column_name");
comboBox.addItem(val);
}
} catch (SQLException ex) {
Logger.getLogger(DefineCustomer.class.getName()).log(Level.SEVERE, null, ex);
}
I suggest putting all of this code inside an ActionListener. So that each time there the mouse is entered over the comboBox the above code will run. You should do the following:
public void mouseEntered(MouseEvent e) {
//the above code goes here
}
I suggest using a mouseListener:
https://docs.oracle.com/javase/tutorial/uiswing/events/actionlistener.html
But if you want to look at other ActionListeners you can see them here:
https://docs.oracle.com/javase/tutorial/uiswing/events/actionlistener.html
Once you add a new registry in the DB, do a removeAllItems comboBox.removeAllItems(); and repopulate de combobox,
My example:
jComboLicorerias.removeAllItems();
try {
Conector = Conecta.getConexion();
Statement St = Conector.createStatement();
try (ResultSet Rs = St.executeQuery(Query)) {
while (Rs.next()) {
jComboLicorerias.addItem(Rs.getString("nombreLicoreria"));
}
St.close();
}
} catch (SQLException sqle) {
JOptionPane.showMessageDialog(null, "Error en la consulta.");
I confused with this if-else because I'm new in Java & MySQL and I tried to make it by myself.
public Menu() {
initComponents();
try {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/restaurant", "root", "");
System.out.println("ODBC Connection Successful");
showCategory();
} catch (ClassNotFoundException | SQLException e) {
System.out.println("ODBC Connection Failed" + e);
}
}
if - else
private void showCategory() {
try {
Statement stmt;
stmt = con.createStatement();
if (rbMFood.isSelected()) {
ResultSet rs = stmt.executeQuery("SELECT * FROM menu_cat WHERE type_id = 'TY02'");
while (rs.next()) {
cmbMCat.addItem(rs.getString("menu_cat"));
}
} else {
ResultSet rs = stmt.executeQuery("SELECT * FROM menu_cat WHERE type_id = 'TY01'");
while (rs.next()) {
cmbMCat.addItem(rs.getString("menu_cat"));
}
}
} catch (Exception e) {
}
}
Radio Button
private void rbMFoodActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
type = "Food";
}
private void rbMDrinkActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
type = "Drink";
}
And I declare the function in the end of the program
private String type;
When I click drink / food, the category still drink's category.
The database
Any help would be greatly appreciated!
You are using rs.getString("menu_cat") But the format is rs.getString(<Column Name>) But you are using rs.getString(<Table Name>) As "menu_cat" is name of the table and not the name of the column.
AFTER POSTING CONSTRUCTOR
What I see from the code you have posted, is that You have called showCategory() in the constructor. This method is responsible for populating the JComboBox cmbMCat. Now the cmbMCat is being populated when you are creating the new Menu. After that the items list of the cmbMCat does not change.
So, What I suggest is that you call the showCategory() from the rbMFoodActionPerformed and rbMDrinkActionPerformed methods. I hope this will solve your problem.
Also add cmbMCat.removeAllItems() before Statement stmt; to remove all the items that are there in the cmbMCat and reset it with a fresh list of items.
After comment regarding the if-else
Change the showCatagory() as below:
private void showCategory() {
cmbMCat.removeAllItems();
try {
PreparedStatement stmt; //Used Prepared statement
String sql = "SELECT * FROM menu_cat WHERE type_id = ?";
stmt = con.prepareStatement(sql);
if (type.equals("Drink")) {
stmt.setString("TY01");
} else {
stmt.setString("TY02");
}
ResultSet rs = stmt.executeQuery();
while (rs.next()) {
cmbMCat.addItem(rs.getString("menu_cat"));
}
}
} catch (Exception e) {
}
}
Also note that you eventListener code should be:
private void rbMFoodActionPerformed(java.awt.event.ActionEvent evt){
type = "Food";
showCategory();
}
private void rbMDrinkActionPerformed(java.awt.event.ActionEvent evt){
type = "Drink";
showCategory();
}
I need help with the code below and getting it to return a true or false value. Any and all help would be appreciated.
public synchronized static boolean checkCompanyName(String companyName,
Statement statement) {
try {
ResultSet res = statement
.executeQuery("SELECT `companyName` FROM `companys` WHERE companyName = '"
+ companyName + "';");
boolean containsCompany = res.next();
res.close();
return containsCompany;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
Try to make your query like this:
ResultSet res = statement.executeQuery("SELECT companyName FROM companys WHERE companyName = " + companyName);
Or you can either you PreparedStatement which is better then you did before
You should be using a PreparedStatement (for that end pass the Connection in to the method). Also, you should retrieve the value from the ResultSet and validate it matches your companyName. Something like
static final String query = "SELECT `companyName` FROM "
+ "`companys` WHERE companyName = ?";
public synchronized static boolean checkCompanyName(String companyName,
Connection conn) {
PreparedStatement ps = null;
ResultSet rs = null;
try {
ps = conn.prepareStatement(query);
ps.setString(1, companyName);
rs = ps.executeQuery();
if (rs.next()) {
String v = rs.getString(1);
return v.equals(companyName);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {
}
}
if (ps != null) {
try {
ps.close();
} catch (SQLException e) {
}
}
}
return false;
}
Two comments:
You only need to check if there's at least one row matching your criteria, so you can use .first()
Your code is vulnerable to SQL Injection attacks. Please read this to learn more about it.
The easiest way to avoid SQL injection attacs is to use prepared statements. So let me strike two birds with a single stone and give you a solution using them:
/*
Check if the company exists.
Parameters:
conn - The connection to your database
company - The name of the company
Returns:
true if the company exists, false otherwise
*/
public static boolean checkCompanyName(Connection conn, String company) {
boolean ans = false;
try(PreparedStatement ps = conn.prepareStatement(
"select companyName from companies where companyName = ?"
) // The question mark is a place holder
) {
ps.setString(1, company); // You set the value for each place holder
// using setXXX() methods
try(ResultSet rs = ps.executeQuery()) {
ans = rs.first();
} catch(SQLException e) {
// Handle the exception here
}
} catch(SQLException e) {
// Handle the exception here
}
return ans;
}
Suggested reads:
Bobby Tables: A guide to preventing SQL injection
The Java Tutorials - JDBC: Using prepared statements