I am trying to populate a JComboBox with data from a database which I have managed to do. The problem is, it populates every time an entry is selected. How do I solve this, I need it to populate once.
public void writeSku() {
try{
Class.forName(dbClass);
connection = DriverManager.getConnection(dbUrl);
state = (Statement) connection.createStatement();
String query2 = "SELECT sku FROM drugs";
result = state.executeQuery(query2);
ResultSetMetaData meta = (ResultSetMetaData) result.getMetaData();
int columns = meta.getColumnCount();
while(result.next()){
for(int i =1; i<=columns; i++){
String skuValue = result.getString(i);
skuCombo4.addItem(skuValue);
}
}
} catch(ClassNotFoundException | SQLException ex){
JOptionPane.showMessageDialog(null,"Error"+ex);
}
}
Related
I want to get the data from the two dates in MySQL and display only the range, however even if it is blank it won't display anything. Moreover, even if I change the simple date format to MM/dd/yyyy the table only display one row and date even I have 2 rows in the database daated 07/14/2022
Here is my code
private void table_stocks(String date_from, String date_to) {
try {
int table;
try {
Class.forName("com.mysql.cj.jdbc.Driver");
con = DriverManager.getConnection(url, username, password);
if(date_from.equals("") || date_to.equals("")){
pst = con.prepareStatement("SELECT `sales_number`, `date`, `amount_due` FROM `dnk_database`.`sales`;");
}
else{
pst = con.prepareStatement("SELECT `sales_number`, `date`, `amount_due`, SUM(`amount_due`) AS `total_sales` FROM `dnk_database`.`sales` WHERE `date` BETWEEN ? AND ?;");
pst.setString(1, date_from);
pst.setString(2, date_to);
}
ResultSet rs = pst.executeQuery();
ResultSetMetaData rsd = rs.getMetaData();
table = rsd.getColumnCount();
DefaultTableModel load = (DefaultTableModel)jTable_salesValue.getModel();
load.setRowCount(0);
while(rs.next()) {
Vector v2 = new Vector();
for(int i = 1; i <= table; i++){
v2.add(rs.getString("sales_number"));
v2.add(rs.getString("date"));
v2.add(rs.getString("amount_due"));
}
load.addRow(v2);
}
} catch (ClassNotFoundException ex) {
Logger.getLogger(Add_Items.class.getName()).log(Level.SEVERE, null, ex);
}
} catch (SQLException ex) {
Logger.getLogger(Add_Items.class.getName()).log(Level.SEVERE, null, ex);
}
}
Also, want to display the SUM of the amount_due column from my SQL to a textfield and I don't know where to place this code
if (rs.next()==true) {
String sum_total = rs.getString("total_sales");
jTextField_totalSales.setText(sum_total);
}
You can accumulate the sum to a variable before the while loop, I assume you are using integer data type, then inside the loop sum the value. After the while loop is done display in the text field
int sumTotal = 0;
while(rs.next()) {
Vector v2 = new Vector();
for(int i = 1; i <= table; i++){
v2.add(rs.getString("sales_number"));
v2.add(rs.getString("date"));
v2.add(rs.getString("amount_due"));
sumTotal += rs.getString("amount_due") == null? 0 : Integer.parseInt(rs.getString("amount_due"));
}
load.addRow(v2);
jTextField_totalSales.setText(sumTotal);
}
I'm trying to import all of the data from mysql database into a jtable using arraylists but something isn't working right, as i get the number of rows right but they're all values of the last row
Here's the code
public ArrayList<medicaments> medicaments_list() {
ArrayList<medicaments> medicament_lists = new ArrayList<medicaments>();
String select_nom_type_med = "select * from medicaments where login=?";
PreparedStatement stmt;
ResultSet rs2;
medicaments med;
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "");
stmt = con.prepareStatement(select_nom_type_med);
stmt.setString(1, Utilisateur.getLogin());
rs2 = stmt.executeQuery();
while (rs2.next()) {
emptytable = false;
med = new medicaments(rs2.getInt("med_id"), rs2.getString("login"), rs2.getString("med_nom"), rs2.getString("med_type"), rs2.getString("date_debut"), rs2.getString("date_fin"), rs2.getString("frequence"), rs2.getString("temps_1"), rs2.getString("temps_2"), rs2.getString("temps_3"), rs2.getString("temps_4"), rs2.getString("temps_5"), rs2.getString("Stock"), rs2.getString("rappel_stock"));
medicament_lists.add(med);
}
} catch (ClassNotFoundException e1) {
System.out.println(e1);
} catch (SQLException e1) {
System.out.println(e1);
}
return medicament_lists;
}
public void populate_jTable_from_db() {
ArrayList<medicaments> dataarray = medicaments_list();
model = (DefaultTableModel) jTable1.getModel();
model.setRowCount(dataarray.size());
int row = 0;
for (medicaments data : dataarray) {
model.setValueAt(data.get_nom_med(), row, 0);
model.setValueAt(data.get_type_med(), row, 1);
row++;
}
jTable1.setModel(model);
}
and here's the result :(there's 3 rows in my database and po is the last one i added)
Make sure your recordset actually contains something and it's what you really want:
while (rs2.next()) {
if (rs2.getString("login").equals(Utilisateur.getLogin())) {
emptytable = false;
med = new medicaments(rs2.getInt("med_id"), rs2.getString("login"),
rs2.getString("med_nom"), rs2.getString("med_type"),
rs2.getString("date_debut"), rs2.getString("date_fin"),
rs2.getString("frequence"), rs2.getString("temps_1"),
rs2.getString("temps_2"), rs2.getString("temps_3"),
rs2.getString("temps_4"), rs2.getString("temps_5"),
rs2.getString("Stock"), rs2.getString("rappel_stock"));
medicament_lists.add(med);
}
}
I'am trying to access data from database and showing it in jTable on clicking a button. but my table shows nothing on pressing button. i have gone through all adding row into table questions in stackOverflow but nothing helped me. here i'am pasting my button's actionListener-
private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
java.util.Date utildate = jDateChooser1.getDate();
java.sql.Date date = new java.sql.Date(utildate.getTime());
//System.out.println(date);
String dbURL = "jdbc:derby://localhost:1527/contact;user=nbuser;password=nbuser";
Connection conn = null;
Statement stmt = null;
try
{
Class.forName("org.apache.derby.jdbc.ClientDriver").newInstance();;
//Get a connection
conn = DriverManager.getConnection(dbURL);
stmt = conn.createStatement();
//System.out.println(id);
ResultSet result = stmt.executeQuery("select ID, NAME from EMPLOYEE ORDER BY ID ");
ArrayList<String> id = new ArrayList<String>();
ArrayList<String> name = new ArrayList<String>();
Map<String, String> present = new HashMap<String, String>();
while(result.next()){
id.add(result.getString("id"));
name.add(result.getString("name"));
present.put(result.getString("id"), "A");
}
result = stmt.executeQuery("select ID from ATTENDANCE where DATE = '" + date +"'");
while(result.next()){
present.replace(result.getString("id"), "P");
}
DefaultTableModel model = (DefaultTableModel) jTable1.getModel();
model.setColumnIdentifiers(new String[] { "Id", "Name","Attendance"});
for(int i = 0; i < id.size(); i++){
System.out.println(id.get(i)+" "+ name.get(i)+ " "+ present.get(id.get(i)));
model.addRow(new String[]{id.get(i), name.get(i), present.get(id.get(i))});
model.fireTableRowsInserted(1, i+1);
}
jTable1.setModel(model);
}
catch (Exception except)
{
except.printStackTrace();
}
}
please tell me where i'am doing wrong?
I coded Auto Suggesting Combo boxes. Functionality is,
*when a user type the first letter in either combo box , data retrieves from the MySQL database and show in a popup list, when a user click on a suggested item ,then press Add button that item added to the J Table and clears the combo boxes
But when I select another item from the combo box and click Add button before added one disappears
*How can I keep Both or many items in the J Table according to above situation *
I'll post my code:
private void NamecomboActionPerformed(java.awt.event.ActionEvent evt) {
String drugname = (String) Namecombo.getSelectedItem();
try{
String name = "SELECT * FROM druginfo WHERE ItemName LIKE '"+drugname+"%'";
PreparedStatement pstmt = conn.prepareStatement(name);
ResultSet rs = pstmt.executeQuery();
while (rs.next()){
IDcombo.setSelectedItem(rs.getString("ItemID"));
}
}catch(Exception e){
JOptionPane.showMessageDialog(null,"error "+ e);
}
}
private void IDcomboActionPerformed(java.awt.event.ActionEvent evt) {
String drugid = (String) IDcombo.getSelectedItem();
try{
String name = "SELECT * FROM druginfo WHERE ItemID LIKE '"+drugid+"%'";
PreparedStatement pstmt = conn.prepareStatement(name);
ResultSet rs = pstmt.executeQuery();
while (rs.next()){
Namecombo.setSelectedItem(rs.getString("ItemName"));
}
}catch(Exception e){
JOptionPane.showMessageDialog(null,"error "+ e);
}
try{
String exp = "SELECT ExpDate FROM druginfo WHERE ItemID LIKE '"+drugid+"%'";
PreparedStatement pstmt = conn.prepareStatement(exp);
ResultSet rs2 = pstmt.executeQuery();
while (rs2.next()){
String date = rs2.getString("ExpDate");
exptxt.setText(date);
}
}catch(Exception e){
JOptionPane.showMessageDialog(null,"error "+ e);
}
}
add button action performed for adding item to JTable;
private void add_btnActionPerformed(java.awt.event.ActionEvent evt) {
String temp = (String) IDcombo.getSelectedItem();
String sql = "select ItemID,ItemName,CostPrice,InStock from druginfo where ItemID=?";
try {
pst=conn.prepareStatement(sql);
pst.setString(1, temp);
rs=pst.executeQuery();
tableSale.setModel(DbUtils.resultSetToTableModel(rs));
IDcombo.setSelectedItem(null);
Namecombo.setSelectedItem(null);
} catch (Exception ex) {
JOptionPane.showMessageDialog(null, ex);
}
Add the current selection(resultset data) to JTable object without replacing the old data.
rs=pst.executeQuery();
addDataToTable(tableSale,DbUtils.resultSetToTableModel(rs));
IDcombo.setSelectedItem(null);
Namecombo.setSelectedItem(null);
//ADD this method
public void addDataToTable(JTable table,TableModel model) {
DefaultTableModel tableModel = (DefaultTableModel) table.getModel();
DefaultTableModel resultSetModel = (DefaultTableModel) model;
for (int i = 0; i < resultSetModel.getRowCount(); i++) {
Vector row=new Vector();
for (int j = 0; j < resultSetModel.getColumnCount(); j++) {
row.addElement(resultSetModel.getValueAt(i, j));
}
tableModel.addRow(row);
}
tableModel.fireTableDataChanged();
}
This tableSale.setModel(DbUtils.resultSetToTableModel(rs)); will replace the old model with new model.So obviously datas will be lost.You have to add values to the existing model.I have added a snippet which will help you.
Replace tableSale.setModel(DbUtils.resultSetToTableModel(rs)); with addValuesToModel(DbUtils.resultSetToTableModel(rs));
addValuesToModel(DbUtils.resultSetToTableModel(rs));
public void addValuesToModel(TableModel resultModel) {
DefaultTableModel tmodel = (DefaultTableModel) tableSale.getModel();
DefaultTableModel rmodel = (DefaultTableModel) resultModel;
for (int i = 0; i < rmodel.getRowCount(); i++) {
Object[] row = new Object[rmodel.getColumnCount()];
for (int j = 0; j < rmodel.getColumnCount(); j++) {
row[j] = rmodel.getValueAt(i, j);
}
tmodel.addRow(row);
}
}
I want to display the data out of my result set into a JTable.
When I run the following code the table doesn't update.
public void getHouses(int price) {
Connection conn;
ArrayList<Integer> ID = new ArrayList<Integer>();
ArrayList<String> Price = new ArrayList<String>();
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
conn = DriverManager.getConnection("jdbc:odbc:Houses");
Statement statement = conn.createStatement();
ResultSet rec = statement.executeQuery("SELECT * FROM Houses WHERE Price <= " + price + "");
while (rec.next()) {
ID.add(rec.getInt("ID"));
Price.add(rec.getString("Price"));
}
String[] columnNames = {"House ID", "House Price"};
Object[][] rows = new Object[ID.size()][2];
for (int i = 0; i < ID.size(); i++) {
rows[i][0] = ID.get(i);
rows[i][1] = Price.get(i);
}
jTable1 = new JTable(rows, columnNames);
statement.close();
} catch (SQLException se) {
} catch (ClassNotFoundException cnf) {}
}
NOTE!
I added the JTable to the gui by drag and drop.
I also tested that my resultset has the data in it.
You need to learn about OP Swing MVC pattern, you need to declare a TableModel which your data store then set it to your table, like:
TableModel myData = new DefaultTableModel(columnVector, dataVector);
jTable1.setModel(myData);
Read more about DefaultTableModel