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();
}
Related
I'am working on this source code :
public class AuthentificationClient extends javax.swing.JFrame {
connexion maconn;
Statement stmt1;
public AuthentificationClient() {
initComponents();
}
private void numcompteActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
}
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
Bienvenue ret = new Bienvenue () ;
ret.setVisible(true);
this.dispose();
}
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
String requete ="Select * from Compte where numcompte='"+numcompte.getText()+"' and codec = '"+Arrays.toString(code.getPassword())+"'";
try {
Statement stmt1 = maconn.Obtenirconnexion().createStatement();
ResultSet rs= stmt1.executeQuery(requete);
} catch (SQLException ex) {
Logger.getLogger(AuthentificationPharmacien.class.getName()).log(Level.SEVERE, null, ex);
}
OpClient oc = new OpClient () ;
oc.setVisible(true);
this.dispose();
}
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new AuthentificationClient().setVisible(true);
}
});
}
There is no error but when I execute, it doesn't work correctly! This is the error message that I receive :
The variable maconn is never assigned, at least in the code you have provided, so you may be calling a method on a null object.
Use PreparedStatement instead of Statement to avoid SQL Injection attack as well to simplify your code e.g. you won't need to enclose string literals within ' ' when you use PreparedStatement.
Perform null check on an object (e.g. maconn) before accessing any member (method/variable) using it.
Do it as follows:
String requete ="Select * from Compte where numcompte = ? and codec = ?";
PreparedStatement pstmt;
ResultSet rs;
try {
if(maconn!=null && maconn.Obtenirconnexion()!=null) {
pstmt = maconn.Obtenirconnexion().prepareStatement(requete);
pstmt.setString(1, numcompte.getText());
pstmt.setString(2, Arrays.toString(code.getPassword()));
rs = pstmt.executeQuery(requete);
//...
}
}
I am designing a simple database application that features 2 jComboBoxes in the GUI. The first jComboBox is populated with the results of an SQL query. I would like the second jComboBox to populate with the results of a second query that incorporates the user selected value in the first box, but I can't quite get it to work.
I have created 2 classes, one that draws the GUI and contains the main method, and a second class that queries my Oracle database.
My GUI class:
public class TestUI extends javax.swing.JFrame {
// Create new form TestUI
public TestUI() {
initComponents();
}
#SuppressWarnings("unchecked")
private void initComponents() {
jPanel1 = new javax.swing.JPanel();
jComboBox1 = new javax.swing.JComboBox<>();
jTextField1 = new javax.swing.JTextField();
jComboBox2 = new javax.swing.JComboBox<>();
jButton1 = new javax.swing.JButton();
jButton2 = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
// Combo box 1 population
jComboBox1.removeAllItems();
createConnection c1 = new createConnection();
c1.getEmployee().forEach((employee) -> {
jComboBox1.addItem(employee);
});
jComboBox1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jComboBox1ActionPerformed(evt);
}
});
// ComboBox 2 population
jComboBox2.removeAllItems();
}
private void jComboBox1ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add handling code here:
}
public static void main(String args[]) {
DRAW GUI
}
}
And my database class:
import java.util.List;
import java.util.ArrayList;
import java.sql.*;
public class createConnection {
String empName;
public Connection createConnection() {
try {
Class.forName(driver);
java.sql.Connection conn = DriverManager.getConnection(DB_URL, DB_username, DB_password);
return conn;
} catch (ClassNotFoundException | SQLException e) {
return null;
}
}
// ComboBox 1
public List<String> getEmployee() {
List<String> list = new ArrayList();
Connection conn = createConnection();
try {
Statement stmt = conn.createStatement();
String query = "SELECT * FROM hr.employees ORDER BY last_name";
ResultSet results = stmt.executeQuery(query);
while (results.next()) {
list.add(results.getString("last_name"));
}
} catch (Exception e) {
System.out.println("Exception = " + e);
}
return list;
}
// Combo Box 2
public List<String> getEmpLocation() {
List<String> list = new ArrayList();
Connection conn = createConnection();
try {
Statement stmt = conn.createStatement();
String query = "SELECT country_id FROM hr.location WHERE hr.location.emp_name = " + empName;
ResultSet results = stmt.executeQuery(query);
while (results.next()) {
list.add(results.getString("last_name"));
}
} catch (Exception e) {
System.out.println("Exception = " + e);
}
return list;
}
}
I have left out irrelevant code like db connection variables and GUI coordinates etc.
I am wondering how to properly get the getEmpLocation() method in the database class to populate the 2nd ComboBox. This will involve adding code to both classes and passing the variable value but I can't figure it out! Any help would be greatly appreciated here.
I'm assuming that you'd like select a value from your first JComboBox then click on a button to process your selected data and load new data to your second JComboBox.
In this case you need an ActionListener to your JButton instead of your JComboBox:
jButton1.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
selectedName = (String) jComboBox1.getSelectedItem();
}
});
You also need to store your selected value in a variable. The getSelectedItem() method returns an Object so it needs to be cast to a String in your case.
Since we added an ActionListener to a button you dont need this one:
jComboBox1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jComboBox1ActionPerformed(evt);
}
});
In your createConnection class (by naming convention class names should start with a capital letter):
If you are not using try-with-resources statement you should close your connections after the catch block.
} finally {
if (conn != null) {
try {
conn.close();
} catch (SQLException ex) {
ex.printStackTrace();
}
}
}
You need to pass your selectedName variable to getEmpLocation() method:
public List<String> getEmpLocation(String name) {
You should use a PreparedStatement instead of Statement:
String query = "SELECT first_name FROM employees WHERE last_name = ?";
PreparedStatement ps = conn.prepareStatement(query);
ps.setString(1, name);
ResultSet results = ps.executeQuery();
To be honest I don't know what you'd like to achieve with your select queries. First, this select query won't work. Table name is LOCATIONS instead of location, and it doesnt have a column called emp_name.
"SELECT country_id FROM hr.location WHERE hr.location.emp_name = ?"
If you'd like to get locations you should use a query like this:
"SELECT dep.department_name, loc.city, cou.country_name
FROM employees emp, departments dep, locations loc, countries cou
WHERE emp.last_name = ?
AND emp.department_id = dep.department_id
AND dep.location_id = loc.location_id
AND loc.country_id = cou.country_id"
You can choose which location you'd like to use department, city or country name. But my main problem is that if you select last names first and put them in a JComboBox it is most likely you will get only one row of data, so there is no point in using the second JComboBox. Let's approach this problem from the other side. What if you select location first and then select your employee. That could solve this issue.
Quick Example:
You select all first names from database, then you can select proper last name.
Selecting all first name from database:
public List<String> getEmpFirstName() {
List<String> list = new ArrayList();
Connection conn = createConnection();
try {
Statement stmt = conn.createStatement();
String query = "SELECT DISTINCT first_name "
+ "FROM hr.employees "
+ "ORDER BY first_name";
ResultSet results = stmt.executeQuery(query);
while (results.next()) {
list.add(results.getString("first_name"));
}
} catch (Exception e) {
System.out.println("Exception = " + e);
} finally {
if (conn != null) {
try {
conn.close();
} catch (SQLException ex) {
ex.printStackTrace();
}
}
}
return list;
}
Selecting last name(s) based on first name using PreparedStatement:
public List<String> getEmpLastName(String name) {
List<String> list = new ArrayList();
Connection conn = createConnection();
try {
String query = "SELECT last_name "
+ "FROM employees "
+ "WHERE first_name = ?";
PreparedStatement ps = conn.prepareStatement(query);
ps.setString(1, name);
ResultSet results = ps.executeQuery();
while (results.next()) {
list.add(results.getString("last_name"));
}
} catch (Exception e) {
System.out.println("Exception = " + e);
} finally {
if (conn != null) {
try {
conn.close();
} catch (SQLException ex) {
ex.printStackTrace();
}
}
}
return list;
}
Update your ActionListener:
jButton1.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
// Store selected value
selectedName = (String) jComboBox1.getSelectedItem();
// Create Connection and pass selected value to getEmpLastName
createConnection c1 = new createConnection();
names = c1.getEmpLastName(selectedName);
// Clear your second comboBox and fill with data
jComboBox2.removeAllItems();
for (String lastName : names) {
jComboBox2.addItem(lastName);
}
}
});
Try to select common names like Alexander, David, James, John, Julia and so on.
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.");
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?
First I create a search function in my program and I implemented the same logic in adding data into the database but the search function works and the add function didn't (SQLException). I created a table from DB2 named Names with only one column FullName. Do you still need to create a new query to add data into the table? or not? I want to add data into the database through GUI.
Here is my Java Code:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.sql.*;
public class ConnectAndSearchDB extends JFrame implements ActionListener
{
private JTextField fieldSearch,fieldAdd;
private JButton searchB,addB;
private Connection connection;
private String name;
private ResultSet rs,rs1;
public ConnectAndSearchDB() throws SQLException,ClassNotFoundException
{
setLocationRelativeTo(null);
setDefaultCloseOperation(this.EXIT_ON_CLOSE);
setLayout(new GridLayout(2,2));
fieldSearch = new JTextField(20);
searchB = new JButton("Search");
fieldAdd = new JTextField(20);
addB = new JButton("Add");
add(searchB);
add(fieldSearch);
add(addB);
add(fieldAdd);
searchB.addActionListener(this);
addB.addActionListener(this);
establishConnection();
pack();
setResizable(false);
setVisible(true);
}
public void actionPerformed(ActionEvent e)
{
Object act = e.getSource();
if(act.equals(searchB))
{
name = fieldSearch.getText();
searchData();
}else if(act.equals(addB))
{
try {
addData();
} catch (ClassNotFoundException e1)
{
e1.printStackTrace();
System.out.println("ClassNotFound");
} catch (SQLException e1)
{
e1.printStackTrace();
System.out.println("SQLError");
}
}
}
public void establishConnection() throws SQLException , ClassNotFoundException
{
Class.forName("com.ibm.db2.jcc.DB2Driver");
connection = DriverManager.getConnection("jdbc:db2://localhost:50000/COLINN", "Colinn","ezioauditore");
}
private void searchData()
{
try
{
PreparedStatement s = null;
String query;
query = "SELECT * from NAMES";
s=connection.prepareStatement(query);
rs = s.executeQuery();
boolean matchfound = false;
while(rs.next())
{
if(rs.getString(1).equals(name))
{
matchfound = true;
System.out.println("The name "+name+" is found in the Database");
break;
}
}
if(matchfound == false)
{
System.out.println("Match Not Found");
}
}
catch(SQLException e)
{
e.printStackTrace();
}
}
public void addData() throws ClassNotFoundException,SQLException
{
PreparedStatement ps = null;
String query;
query = "INSERT INTO NAMES VALUES('"+fieldAdd.getText()+"')";
ps = connection.prepareStatement(query);
rs1 = ps.executeQuery();
System.out.println("Written Successfully");
}
public static void main (String args[]) throws SQLException,ClassNotFoundException
{
EventQueue.invokeLater(new Runnable()
{
public void run()
{
try
{
new ConnectAndSearchDB();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
}
Here is the Names table:
I highly suspect that using rs1 = ps.executeQuery(); to insert/update the database is the course of your issue, you should be using int count = ps.executeUpdate();
See PreparedStatement#executeUpdate for more details
Not an answer per se, but a series of extended comments about some issues with the overall approach...
Lesson #1 - Resource management
If you open it, you should close it...
String query = "SELECT * from NAMES";
try (PreparedStatement stmt = connection.prepareStatement(query)) {
try (ResultSet rs = s.executeQuery()) {
boolean matchfound = false;
while(rs.next())
{
if(rs.getString(1).equals(name))
{
matchfound = true;
System.out.println("The name "+name+" is found in the Database");
break;
}
}
if(matchfound == false)
{
System.out.println("Match Not Found");
}
}
catch(SQLException e)
{
e.printStackTrace();
}
See The try-with-resources Statement for more details...
I'd also reconsider using a single Connection, while a Connection pool might be overkill for this problem, you could simply open and close a Connection as need, but remember, there is an overhead incurred when doing this...
Lesson #2 - Don't do what the database can do better
String query = "SELECT count(*) from NAMES where name=?";
try (PreparedStatement stmt = connection.prepareStatement(query)) {
stmt.setString(1, name);
try (ResultSet rs = s.executeQuery()) {
boolean matchfound = false;
if (rs.next())
{
if(rs.getLong(1) > 0)
{
matchfound = true;
System.out.println("The name "+name+" is found in the Database");
}
}
if(!matchfound)
{
System.out.println("Match Not Found");
}
}
catch(SQLException e)
{
e.printStackTrace();
}
Lesson #3 - Make use of your PreapredStatement...
Instead of...
query = "INSERT INTO NAMES VALUES('"+fieldAdd.getText()+"')";
Use...
query = "INSERT INTO NAMES VALUES(?)";
//...
ps.setString(1, fieldAdd.getText());
See Using Prepared Statements