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)
Related
In my SQL database single record consists of four rows: id, name, age and email. How to get a single record by typing in a JTextField id of that record? So later we can for example System.out.printIn(); it? I know that my question might be stupid for someone who is an SQL expert but I am only a beginner and after searching for this information in the tutorials I could not find it:(. Please help. Here is some of my source code:
public static Connection getConnection() throws Exception{
try{
String driver = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://some IP address/testdb";
String username = "some username";
String password = "some password";
Class.forName(driver);
Connection conn = DriverManager.getConnection(url,username,password);
System.out.println("Connected");
return conn;
} catch(Exception e){System.out.println(e);}
return null;
}
public EsquelTest() {
IDname = new JTextField("");
submit = new JButton("go");
add(IDname);
add(submit);
submit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(e.getSource() == submit) {
id = IDname.getText().toString();
try {
getConnection();
get(id);
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}
});
setLayout(new GridLayout());
}
public static ArrayList<String> get(String idname) throws Exception{
try{
Connection con = getConnection();
PreparedStatement statement = con.prepareStatement("Statement needed to get the whole record by owning only an ID");
ResultSet result = statement.executeQuery();
ArrayList<String> array = new ArrayList<String>();
while(result.next()){
array.add(result.getString("last"));
}
System.out.println("All records have been selected!");
return array;
}catch(Exception e){System.out.println(e);}
return null;
}
If you are asking for only SQL statement it is: select * from yourtable where id = theIdThatIsfromTextFieldHere
Yet, if you simply google it you will find thousands of answers. here for instance.
The SQL Statement would be SELECT * FROM yourtable WHERE id = yourid. So to embed it into your code it would look something like this:
public static Connection getConnection() throws Exception{
try{
String driver = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://some IP address/testdb";
String username = "some username";
String password = "some password";
Class.forName(driver);
Connection conn = DriverManager.getConnection(url,username,password);
System.out.println("Connected");
return conn;
} catch(Exception e){System.out.println(e);}
return null;
}
public EsquelTest() {
IDname = new JTextField("");
submit = new JButton("go");
add(IDname);
add(submit);
submit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(e.getSource() == submit) {
id = IDname.getText().toString();
try {
getConnection();
get(id);
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}
});
setLayout(new GridLayout());
}
public static ArrayList<String> get(String idname) throws Exception{
try{
Connection con = getConnection();
PreparedStatement statement = con.prepareStatement("SELECT * FROM {REPLACE WITH YOUR TABLE} WHERE id = "+idname);
ResultSet result = statement.executeQuery();
ArrayList<String> array = new ArrayList<String>();
while(result.next()){
array.add(result.getString("last"));
}
System.out.println("All records have been selected!");
return array;
}catch(Exception e){System.out.println(e);}
return null;
}
Just a Tip: Don't name you function "get" as this is a commonly used keyword in other programming languages that only causes confusion.
Try it:
public static Connection getConnection() throws Exception{
try{
String driver = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://some IP address/testdb";
String username = "some username";
String password = "some password";
Class.forName(driver);
Connection conn = DriverManager.getConnection(url,username,password);
System.out.println("Connected");
return conn;
} catch(Exception e){System.out.println(e);}
return null;
}
public EsquelTest() {
IDname = new JTextField("");
submit = new JButton("go");
add(IDname);
add(submit);
submit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(e.getSource() == submit) {
id = IDname.getText().toString();
try {
getConnection();
for(String string:get(id)){
System.out.println(string);
}
// get(id);
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}
});
setLayout(new GridLayout());
}
public static ArrayList<String> get(String idname) throws Exception{
try{
Connection con = getConnection();
// You should replace "YourTableName" With table in databace that you work with it
PreparedStatement statement = con.prepareStatement("SELECT * FROM YourTableName WHERE id = '" + idName+"'");
//If type of your id in database is Int write this code :
// int id= Integer.parseInt(idName);
//PreparedStatement statement = con.prepareStatement("SELECT * FROM YourTableName WHERE id = " + idName);
ResultSet result = statement.executeQuery();
ArrayList<String> array = new ArrayList<String>();
result.next();
//This array has all data in single recorde
array.add(result.getString("id"));
array.add(result.getString("name"));
array.add(result.getString("age"));
array.add(result.getString("email"));
// I removed this rows becuse you have only one record
// while(result.next()){
//
// array.add(result.getString("last"));
// }
System.out.println("All records have been selected!");
return array;
}catch(Exception e){System.out.println(e);}
return null;
}
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
}
}
Im developing java desktop application for my college assignment. I have encounter a problem while i'm loading values to the Jtable. I used following code to load values. It makes duplicate entries. Can you please help me to get rid of this issue?
private void LoadSupplierTable() {
clearTable((javax.swing.table.DefaultTableModel) tblSupp.getModel());
javax.swing.table.DefaultTableModel dtSupp = (javax.swing.table.DefaultTableModel) tblSupp.getModel();
Vector ver = new Vector();
try {
ResultSet resO = null;
String sqo = "select id,name from supplier";
Connection coo = DataBaseConnection.getDbConnection();
PreparedStatement pso = coo.prepareStatement(sqo);
resO = pso.executeQuery();
while (resO.next()) {
ver.add(resO.getInt("id"));
ver.add(resO.getString("name"));
dtSupp.addRow(ver);
}
} catch (Exception e) {
e.printStackTrace();
}
}
You should declare the vector inside the while loop... just copy paste the following code
private void LoadSupplierTable() {
clearTable((javax.swing.table.DefaultTableModel) tblSupp.getModel());
javax.swing.table.DefaultTableModel dtSupp = (javax.swing.table.DefaultTableModel) tblSupp.getModel();
try {
ResultSet resO = null;
String sqo = "select id,name from supplier";
Connection coo = DataBaseConnection.getDbConnection();
PreparedStatement pso = coo.prepareStatement(sqo);
resO = pso.executeQuery();
while (resO.next()) {
Vector ver = new Vector();
ver.add(resO.getInt("id"));
ver.add(resO.getString("name"));
dtSupp.addRow(ver);
}
} catch (Exception e) {
e.printStackTrace();
}
}