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
Related
My table in java is connected to mysql. It retrieves data in the table. but when i specified getrowcount() it shows 0 rows in system.out.print. pls help, our project deadline is on 3rd june.
DefaultTableModel model = (DefaultTableModel) table.getModel();
model.setRowCount(0);
try{
Class.forName("com.mysql.cj.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/project","root","tiger");
stmt = conn.createStatement();
if(ch1.isSelected()){
String query = "Select * from details where name like '"+d2.getText()+"%';";
rs = stmt.executeQuery(query);
System.out.print(table.getRowCount());
}
if(table.getRowCount() == 0){
JOptionPane.showMessageDialog(null,"No records found");
}
while(rs.next()){
int id;
id = rs.getInt("userid");
String name = rs.getString("name");
String gender = rs.getString("gender");
String dob = rs.getString("dob");
String phno = rs.getString("phoneno");
String doj = rs.getString("joindate");
String doe = rs.getString("exitdate");
model.addRow(new Object[]{id,name,gender,dob,phno,doj,doe});
}
rs.close();
stmt.close();
conn.close();
}
catch(ClassNotFoundException | SQLException e){
JOptionPane.showMessageDialog(null,"Error");
}
d1.setText("");
d2.setText("");
d3.setSelectedItem("");
d4.setText("");
d5.setText("");
d6.setText("");
d7.setText("");
update.setEnabled(false);
delete.setEnabled(false);
Please check below what does getRowCount() gives you
You can refer the below link for more clarification
https://docs.oracle.com/javase/8/docs/api/javax/swing/JTable.html#getRowCount--
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 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
The program have to download data from MySQL database. and fill the JList. I want to bind this data.
Here you have a code:
Connection connection = null;
String dbtime;
String query = "Select * FROM EMP";
String[] celDatas = null;
String[] celNames = null;
try {
(...)
Statement stmt = connection.createStatement();
ResultSet rs = stmt.executeQuery(query);
ResultSetMetaData rsmd = rs.getMetaData();
int NumOfCol = rsmd.getColumnCount();
celNames = new String[NumOfCol];
celDatas = new String[NumOfCol];
for(int weq=1; weq<=NumOfCol; weq++) {
System.out.println(rsmd.getColumnName(weq));
celNames[weq-1] = rsmd.getColumnName(weq);
while (rs.next()) {
dbtime = rs.getString(weq);
System.out.println(dbtime);
celDatas[weq-1] = dbtime;
}
rs = stmt.executeQuery(query);
System.out.println();
}
} catch (ClassNotFoundException e) {
} catch (SQLException e) {
}
final JList source = new JList(celDatas,celNames);
JScrollPane pane = new JScrollPane(source);
pane.setSize(f.getSize().width-60,300);
pane.setLocation(30,20);
I have a problem with
final JList source = new JList(celDatas,celNames);
It shows this problem in Netbeans: http://dl.dropbox.com/u/8455739/Java-Problem.png
//String[] celDatas = null;
String[][] celDatas = null;
String[] celNames = null;
...
//final JList source = new JList(celDatas,celNames);
final JTable source = new JTable(celDatas,celNames);
Here's my code:
private void show(java.awt.event.ActionEvent evt) {
Connection conn = null;
String url = "jdbc:mysql://localhost:3306/";
String dbName = "phone";
String driver = "com.mysql.jdbc.Driver";
String userName = "root";
String password = "school";
try {
Class.forName(driver).newInstance();
conn = DriverManager.getConnection(url + dbName, userName, password);
PreparedStatement pStmt = conn.prepareStatement("SELECT * FROM contacts");
ResultSet rs = pStmt.executeQuery();
JFrame frame1 = new JFrame();
frame1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame1.setSize(300, 150);
frame1.setVisible(true);
while (rs.next() == true) {
Object rowData[][] = {{"Name"},
{"Phone"}};
Object columnNames[] = {"Column One", "Column Two"};
JTable table = new JTable(rowData, columnNames);
JScrollPane scrollPane = new JScrollPane(table);
frame1.add(scrollPane, BorderLayout.CENTER);
}
rs.close();
pStmt.close();
conn.close();
} catch (Exception ex) {
System.out.println(ex);
}
}
I want to display the record in a separate window but its showing a blank screen. Any corrections suggested?
Vector columnNames = new Vector();
Vector data = new Vector();
try{
Connection conn = null;
DriverManager.registerDriver(new oracle.jdbc.OracleDriver());
conn = DriverManager.getConnection(
"jdbc:oracle:thin:#localhost:1521:XE","yedal ","yedal121288");
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("");
ResultSetMetaData meta=rs.getMetaData();
int columns = meta.getColumnCount();
for (int i = 1; i <= columns; i++)
{
columnNames.addElement( meta.getColumnName(i) );
}
while (rs.next())
{
Vector row = new Vector(columns);
for (int i = 1; i <= columns; i++)
{
row.addElement( rs.getObject(i) );
}
data.addElement( row );
}
rs.close();
stmt.close();
}
catch (SQLException ex) {
ex.printStackTrace();
}
t= new JTable(data, columnNames); t.setVisible(true);
TableColumn col;
for (int i = 0; i < t.getColumnCount(); i++)
{
col = t.getColumnModel().getColumn(i);
col.setMaxWidth(200);
}
JScrollPane scrollPane = new JScrollPane(t);
You're creating multiple JTables in your while loop, I assume that's not what you're intending to do, and also you don't give them size. you must set the size of JTable with setPreferredSize or setSize method:
tblObj.setPreferredSize(new Dimension(300,400));
also you pass true to setFillsViewportHeight method for your table content to fill the view port.
Here's a link on how to use JTable:
How To Use JTable
I suppose you see an exception java.lang.ArrayIndexOutOfBoundsException if you look into your console. The JTable is populated with a table model which has two columns but you construct it with an array with data of only one.
Please note since you set the frame to visible before this exception occurs, the frame is shown, the component is added to it but when swing tries to paint it it will fail.
If you replace your test data with e.g.
Object rowData[][] = { { "Name", "Phone" }, { "Name2", "Phone2" } };
it'll work (unless rs.next() is never true).
it is better to use a library file rs2xml.jar .
include it into ur library
first create a connection with the database using jdbc.
import this --> import net.proteanit.sql.DbUtils;
String query ="select * from employee"; //let
pst = conn.prepareStatement(query);
rs = pst.executeQuery();
s.append (QueryArea.getText()).append("\n");
jTable.setModel(DbUtils.resultSetToTableModel(rs));
There will be an exception thrown in this ,so handle it by a try catch statement.
if any problem with this u can ask.