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?
Related
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);
}
}
Am trying to load the results of a database into a jtable, but when i run the code it only displays the first row and then errors an exception that no data was found. Here is my code;
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
String url = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb, *.accdb)};DBQ=" + "C:\\Users\\PMatope.FMBMW.000\\Documents\\Library.accdb";
conn = DriverManager.getConnection(url, "", "");
st = conn.createStatement();
ResultSet rs = st.executeQuery("SELECT ID,full_name,sex,course,contact,email FROM Person");
ResultSetMetaData data = rs.getMetaData();
DefaultTableModel model = (DefaultTableModel) jTable1.getModel();
// jTable1.setModel(model);
while (rs.next()) {
String id,fname,sex,course,contact,email;
id = rs.getString("ID");
fname = rs.getString("full_name");
sex = rs.getString("sex");
course = rs.getString("course");
contact = rs.getString("contact");
email = rs.getString("email");
model.addRow(new Object[] {id,fname,sex,course,contact,email});
model.fireTableDataChanged();
JOptionPane.showMessageDialog(null, rs.getString("sex"));
}
} catch (Exception e) {
JOptionPane.showMessageDialog(null,"Message: "+ e.getMessage());
}
Declare your table model first and create new instance for each loop times.
eg. :
DefaultTableModel model = null;
// jTable1.setModel(model);
while (rs.next()) {
model = (DefaultTableModel) jTable1.getModel();
String id,fname,sex,course,contact,email;
id = rs.getString("ID");
fname = rs.getString("full_name");
sex = rs.getString("sex");
course = rs.getString("course");
contact = rs.getString("contact");
email = rs.getString("email");
model.addRow(new Object[] {id,fname,sex,course,contact,email});
model.fireTableDataChanged();
JOptionPane.showMessageDialog(null, rs.getString("sex"));
}
You need to initialise,
DefaultTableModel model = (DefaultTableModel) jTable1.getModel();
inside your while loop
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
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);
}
}
I am new to Java and I am practicing some new stuff.. I've started working with the database. therefore I made a to do list application with the MVC pattern.
In my Model I get all the results. In My view I try to output this data as a nice table. The problem is that I don't get any output except for a hardcoded piece of code..
here is the code of my view
JTable table = null;
public ToDoListView(ToDoListModel model) {
this.model = model;
setBackground(Color.WHITE);
JTable table = new JTable();
DefaultTableModel tableModel = new DefaultTableModel(new Object[][]{},new String[]{"To do","Date added"});
table.setModel(tableModel);
// this one below is outputted
tableModel.addRow(new Object[]{"something","1-1-2012"});
// this should give me all the results..
for(int i = 0; i < model.getRows().size(); i++) {
tableModel.addRow(model.getRows());
System.out.println("added");
}
add(table);
}
in my Model I have this
private Vector<String> rijen = new Vector<String>();
public void getValue() {
Connection con = null;
Statement st = null;
ResultSet rs = null;
try {
con = db.connectToAndQueryDatabase("test", "root", "root");
System.out.println("connection established");
st = con.createStatement();
String query = "SELECT id, item, datum FROM toDoList";
rs = st.executeQuery(query);
while(rs.next()) {
System.out.println(rs.getInt("id") + "\n" + rs.getString("item") + "\n" + rs.getDate("datum"));
rijen.add(rs.getInt("id") + "");
rijen.add(rs.getString("item"));
rijen.add(rs.getDate("datum") + "");
}
public Vector<String> getRows() {
return rijen;
}
This is all the relevant code.. I don't know what I miss or what I do wrong. Could someone show me how I could solve it :)?
// This JTable attribut ...
JTable table = null;
public ToDoListView (ToDoListModel model) {
this.model = model;
setBackground (Color.WHITE);
// is hidden by this local variable:
JTable table = new JTable();
In your ToDoModel class you add all data in one large Vector
while(rs.next()) {
System.out.println(rs.getInt("id") + "\n" + rs.getString("item") + "\n" + rs.getDate("datum"));
rijen.add(rs.getInt("id") + "");
rijen.add(rs.getString("item"));
rijen.add(rs.getDate("datum") + "");
}
Then you loop over that Vector to add all those items to the TableModel, but that loop is incorrect
for(int i = 0; i < model.getRows().size(); i++) {
tableModel.addRow(model.getRows());
System.out.println("added");
}
You always add the whole vector instead of just the data for that row.
Combine that with the answer of #user unknown and you might be able to fix your problem