public Boolean load() {
Connection con = null;
PreparedStatement pre = null;
Boolean isexist = false;
try {
con = DBManager.getConnection();
String sql = "SELECT * FROM contacts WHERE mobile=?";
pre = con.prepareStatement(sql);
pre.setString(1, this.mobile);
ResultSet result = pre.executeQuery();
if (result.next()) {
isexist = true;
}
} catch (Exception e) {
} finally {
if (pre != null) {
try {
pre.close();
} catch (Exception e) {
e.printStackTrace();
}
}
if (con != null) {
try {
con.close();
} catch (Exception e) {
}
}
}
return isexist;
}
// and in actionListner `
Contacts objj=new Contacts(this.mobile.getText());
if (objj.load())
{
this.name.setText("njkn");
this.mobile.setText("jbnlj");
this.address.setText("jnl");
this.email.setText("knkl");
} else
{
JOptionPane.showMessageDialog(null," error message");
}
I created 4 text fields in JFrame and I want when user put the mobile num then click on search button - display other information (name, email, address) but the it is display
You need to pass the mobile number to the load function as argument, otherwise you can't use it as a parameter for your search.
You need to somehow get the returned values back, either via return or with fields or smt.
You can use try with resources blocks for any autocloseable, like Connection or PreparedStatement.
I added more comments in the code.
// I use hashmap as a return value, the hashmap contains the values from the db
public static HashMap<String, String> load(String mobile) { // You need to pass the number you're looking for
String sql = "SELECT email, name, address FROM people WHERE mobile=?"; // You only need to return the columns you need
try (
Connection conn = DriverManager.getConnection(LOCATION);
PreparedStatement pre = conn.prepareStatement(sql)) { // try with ressources so that the connection and preparedstatement close automatically at the end
pre.setString(1, mobile); // enter the passed mobile variable in the query
ResultSet result = pre.executeQuery();
if (result.next()) {
// You need to return the values from the db somehow
HashMap<String, String> information = new HashMap<>();
information.put("email", result.getString("email")); // Get the value in the "email" column and store it with the "email" key
information.put("address", result.getString("address")); // Get the value in the "address" column and store it under "address" key
information.put("name", result.getString("name")); // Get the value in the "name" column and store it under "name" key
return information;
// You don't need to check if the values exist. If they don't exist it will just return null and you can check that when you call
}
} catch (Exception e) {
System.out.println(e.getMessage());
}
return null; // return null if the values don't exist
}
// Sample method to build GUI
// I just used this to test everything was working, if you already have a GIU you don't need it
public void GUI() {
JFrame frame = new JFrame();
Container contentPane = frame.getContentPane();
contentPane.setLayout(new BoxLayout(contentPane, BoxLayout.Y_AXIS));
JLabel label = new JLabel("enter mobile number and click search");
JTextField name = new JTextField("name");
JTextField mobile = new JTextField("mobile");
JTextField address = new JTextField("address");
JTextField email = new JTextField("email");
JButton button = new JButton("Search");
button.addActionListener(e -> {
try { // try in case the method returns null
HashMap<String, String> information = load(mobile.getText());
// set the textfields with the returned values
email.setText(information.get("email"));
address.setText(information.get("address"));
name.setText(information.get("name"));
} catch (NullPointerException ex) { // catch the exception for when the entered number was invalid
label.setText("Invalid number"); // set error message
}
});
contentPane.add(label);
contentPane.add(mobile);
contentPane.add(name);
contentPane.add(email);
contentPane.add(address);
contentPane.add(button);
frame.pack();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
Related
I am trying to create program which will display or hide button depended on role of the user, depend if user is Administrator or someone else.
So in this case i am passing String from "Login" frame to "Menu" frame and if is String equal to my requirement, it show button, if is not, then hide button, on "Menu" frame. Now this is working with string. But how to do same thing but to pull Role from database? I have that field in database but i don't know how exactly to do that. - My fields in database are username, password and role.
Thanks!
Login frame
JButton btnLogin = new JButton("Login !");
btnLogin.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
String username = textUsername.getText();
String password = passwordField.getText();
String S = "Administrator";
String query = "SELECT * FROM ADMINISTRATION where username=? and password=?;";
PreparedStatement stmt = connection.prepareStatement(query);
stmt.setString(1, username);
stmt.setString(2, password);
ResultSet set=stmt.executeQuery();
if (set.next()) {
Menu menu = new Menu();
menu.setVisible(true);
setVisible(false);
menu.Proba(S);
stmt.close();
connection.close();
}
else {
JOptionPane.showMessageDialog(contentPane, "Pogrešno korisničko ime ili lozinka !", "Greška !", JOptionPane.ERROR_MESSAGE);
}
} catch (Exception e2) {
// TODO: handle exception
}
}
});
Menu frame
public void Proba(String S) {
if (S.equals("Administrator")) {
btnOption.setVisible(true);
}
else {
btnOption.setVisible(false);
}
}
Ok, I'm assuming this is an academic project.
So, you have a ResultSet and you are iterating over it, when you call the "next" method you move to the next (in this case the first) row.
Now you have a row, you need to call a method that retrieves a String value from a column (in this case role), check the documentation:
https://docs.oracle.com/javase/7/docs/api/java/sql/ResultSet.html
You have a "getString" method that needs a column name, and will return the string valuo from that column.
An example could be:
if (set.next()) {
String role = set.getString("role");
Menu menu = new Menu();
menu.setVisible(true);
setVisible(false);
menu.Proba(role);
stmt.close();
connection.close();
}
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.");
I am trying to pass data from a db in another class into JFrame in jcombobox but only the last row is displayed. Below is a sample code:
Class A...
public String jcbNames() {
try {
con = connCC.getDBconnection();
stm = con.createStatement();
ResultSet rs = stm.executeQuery("Select customerName From appointment");
while (rs.next()) {
customer = (rs.getString(1));
}
con.close();
} catch (SQLException ex) {
ex.printStackTrace();
} catch (ClassNotFoundException ex) {
Logger.getLogger(Appointment.class.getName()).log(Level.SEVERE, null, ex);
}
return customer;
}
Class JFrame...
private void jCBCustomersActionPerformed(java.awt.event.ActionEvent evt) {
Appointment app = new Appointment();
this.jCBCustomers.removeAllItems();
this.jCBCustomers.addItem(app.jcbNames());
}
the problem is there you return just one String in your jcbNames method , use an arraylist and add all of strings to it and then return it as a collection of database data.
so change your methods or use this modified methods.
public ArrayList<String> jcbNames() {
try {
con = connCC.getDBconnection();
stm = con.createStatement();
ResultSet rs = stm.executeQuery("Select customerName From appointment");
ArrayList<String> list = new ArrayList<>();
while (rs.next()) {
list.add(rs.getString(1));
}
con.close();
} catch (SQLException ex) {
ex.printStackTrace();
} catch (ClassNotFoundException ex) {
Logger.getLogger(Appointment.class.getName()).log(Level.SEVERE, null, ex);
}
return list;
}
and
private void jCBCustomersActionPerformed(java.awt.event.ActionEvent evt) {
Appointment app = new Appointment();
this.jCBCustomers.removeAllItems();
ArrayList<String> list =app.jcbNames();
for (String str:list){
this.jCBCustomers.addItem(str);
}
}
and if you don't want to use this.jCBCustomers.removeAllItems(); to prevent duplicates , use below code
private void jCBCustomersActionPerformed(java.awt.event.ActionEvent evt) {
Appointment app = new Appointment();
// collect all of your current data in jcombobox
ArrayList<String> current_list = new ArrayList<>();
int count = this.jCBCustomers.getItemCount(); // get count of them
for (int i = 0; i < count; i++) {
current_list.add((String) this.jCBCustomers.getItemAt(i)); // add them to current list
}
// data that returned from database
ArrayList<String> returned_from_db_list = jcbNames(); // calling jcbNames method
/*
for each string that has returned from database ,
if it doesn't in the current_list
you can add it to jcombobox , so ...
*/
for (String str : returned_from_db_list) {
if ( !current_list.contains(str) ) { // check for existing in the current_list
current_list.add(str); // adding fresh data to current_list!
/*
or you can add them directly to jcombobox and remove above statement.
this.jCBCustomers.addItem(str); // add updated data to jcombobox
*/
}
}
/*
if ::: you use current_list.add(str); in above for-each-loop ,
now you must update jcombobox data !
else ::: remove below loop.
*/
for (String singleStr : current_list) {
this.jCBCustomers.addItem(singleStr); // add updated data to jcombobox
}
}
When I return vector data using elementAt(2), I am getting this output.
Hello [162, Experiment 3.doc, E:\Desktop\Experiment 3.doc, doc, 35.5 kb]
I want the index value: "Experiment 3.doc".
// Function to fetch data from Database and store in jtable
public Vector getEmployee(String searchQuery)throws Exception
{
Connection con = null;
try{
Class.forName(driver);
} catch(java.lang.ClassNotFoundException e) {
e.printStackTrace();
}
try{
Vector<Vector<String>> employeeVector = new Vector<>();
con = DriverManager.getConnection(url,"conjure","conjure");
String query = "SELECT * FROM APP.FILES WHERE NAME LIKE '%"+searchQuery+"%'";
Statement st = con.createStatement();
ResultSet rs = st.executeQuery(query);
while(rs.next()) {
Vector<String> file = new Vector<>();
file.add(rs.getString(1)); //Empid
file.add(rs.getString(2)); //name
file.add(rs.getString(3)); //position
file.add(rs.getString(4)); //externsion
file.add(rs.getString(5)); //size
employeeVector.add(file);
}
rs.close();
return employeeVector;
} catch (Throwable err) {
err.printStackTrace();
System.out.println("Inside two");
} finally {
con.close();
}
return null;
}
// Button click, show data in jtable.
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt)
{
String searchQuery = jTextField1.getText();
//get data from database
DBEngine dbengine = new DBEngine();
try {
data = dbengine.getEmployee(searchQuery);
System.out.println("Hello "+data.elementAt(2));
jTable1.setModel(new DefaultTableModel(data,header));
} catch (Exception ex) {
ex.printStackTrace();
}
}
Now I want to use column 3, i.e. filename (Experiment 3.doc) somewhere else.
How can I do that?
You have a Vector of Vectors.
data.elementAt(2) will return a Vector of Strings. You then need to get the next element from this resulting Vector, presumably data.elementAt(2).getElementAt(2)