JTable only displaying one colum from access database - java

I'm trying to display the data from a access database; for some reason, whenever I run the program, only one row is displayed. Here's my code
try{
String coursec = jTextField9.getText().trim();
String sql5 = "SELECT * FROM Studentcourse WHERE ccode ='" +coursec+"'";
String url5 ="jdbc:ucanaccess://C:/Users/james_000/Documents/NetBeansProjects/Registration/Campus.accdb ";
Connection conn5 =DriverManager.getConnection(url5);
Statement statem = conn5.createStatement();
ResultSet rs5 = statem.executeQuery(sql5);
while (rs5.next()){
DefaultTableModel dm;
dm = new DefaultTableModel(10, 10);
String coursecode= rs5.getString(2);
String attend =rs5.getString(3);
String date =rs5.getString(4);
Vector <String> vector = new Vector<String>();
vector.add(coursecode);
vector.add(attend);
vector.add(date);
String s[] = new String[]{"ccode", "stnumattend", "Date"};
dm.setColumnIdentifiers(s);
jTable1.setModel(dm);
dm.addRow(vector);
jTable1.setVisible(true);
}
}
catch(Exception d){
System.err.println("Exception:" + d.getMessage());
}

You're creating a new DefaultTableModel each time through your while loop, so only the last such model is applied to jTable1. At a minimum, move the model creation out of the loop.
DefaultTableModel dm = new DefaultTableModel(10, 10);
jTable1.setModel(dm);
while (rs5.next()) {
String coursecode= rs5.getString(2);
…
}

Related

How to fill jtable with the right data from another table?

I have a JTable with 6 columns, the rows for the first 3 columns comes from table1(subject_records_bsit_first_year) and the last 3 will come from table2(evaluation_permission). The two database table have two joined columns(subject_code and subject_title). I'm trying to fill the last 3 columns of my JTable with data from table2—using the db table connection to display the right data.
My code:
public static void loadFirstYearSubjectList() {
ConnectionManager connectionManager = new ConnectionManager();
//String sqlChooseStudent = "SELECT * FROM student_bsit_"+studentID.toLowerCase() +" WHERE year_level = '"+yearLevel+"'";
try {
Connection con = connectionManager.createConnection();
Statement stmt = con.createStatement();
String sql = "SELECT * FROM `subject_records_bsit_first_year` ORDER BY `subject_records_bsit_first_year`.`trimester_period` ASC";
ResultSet rs = stmt.executeQuery(sql);
DefaultTableModel tableModel = new DefaultTableModel();
tableModel.addColumn("Subject Code");
tableModel.addColumn("Subject Title");
tableModel.addColumn("Trimester");
tableModel.addColumn("Section");
tableModel.addColumn("Professor");
tableModel.addColumn("Evaluation");
table.setModel(tableModel);
TableColumnModel columnModel = table.getColumnModel();
columnModel.getColumn(0).setPreferredWidth(95);
columnModel.getColumn(1).setPreferredWidth(266);
columnModel.getColumn(2).setPreferredWidth(90);
columnModel.getColumn(3).setPreferredWidth(77);
columnModel.getColumn(4).setPreferredWidth(179);
columnModel.getColumn(5).setPreferredWidth(78);
DefaultTableCellRenderer renderer = new DefaultTableCellRenderer();
renderer.setBackground(new Color(120, 120, 120, 10));
renderer.setOpaque(true);
columnModel.getColumn(0).setCellRenderer(renderer);
columnModel.getColumn(1).setCellRenderer(renderer);
columnModel.getColumn(2).setCellRenderer(renderer);
columnModel.getColumn(3).setCellRenderer(renderer);
columnModel.getColumn(4).setCellRenderer(renderer);
columnModel.getColumn(5).setCellRenderer(renderer);
while (rs.next()) {
String subjectCode = rs.getString("subject_code");
String subjectTitle = rs.getString("subject_title");
String trimesterPeriod = rs.getString("trimester_period");
tableModel.addRow(new Object[] {subjectCode, subjectTitle, trimesterPeriod});
}
} catch (Exception e) {
} finally {
try {
connectionManager.closeConnection();
} catch (Exception e2) {
}
}
}
table 2 data
I'm trying to display the section, subject_teacher and evaluation_permission from this table, this table is joined from another table that already displays the first 3 columns on my jtable. The two db table is joined with the same column names; subject_code and subject_title.
Create your own implementation of TableModel that is able to retrieve the data as you described above. Then use JTable's setModel() to make the JTable actually use your TableModel implementation.
An example how to use it is in the Java tutorials.
SELECT subject_records_bsit_first_year.subject_code,
subject_records_bsit_first_year.subject_title,
subject_records_bsit_first_year.trimester_period,
evaluation_permission.section, evaluation_permission.subject_teacher,
evaluation_permission.permission_status
FROM subject_records_bsit_first_year
INNER JOIN evaluation_permission
ON subject_records_bsit_first_year.subject_code = evaluation_permission.subject_code;
Got what I'm trying to do, thanks for the help! Sometimes people learn from example.

How to clear all data inserted in a jTable

I designed a jTable that will display data from a table in MySql DB.
The table name is studentrolls with STRollID (int) as primary key and StudentID (Varchar), BachID (year) as foreign keys.
So after typing the StudentID in a jTextField and clicking a jButton only data concerning the student should be displayed in the jTable.
It's working actually but am having two problems, instead of displaying the Year on the year column it's displaying a date for example it should display 2020 but it displaying 2020-01-01.
The main problem is that when I enter another StudentID, it is adding the new results to the old one, so when I enter for the first time a StudentID I get good results and then when I enter another StudentID and click the button I get in the table the new results mixed with the first student's one, etc...
Is there any way to solve this and clear the table before inserting new results?
Here is my code :
private void rSButtonIconDsearchstidActionPerformed(java.awt.event.ActionEvent evt) {
try{
String sqlqueryPastYHi = "SELECT * FROM studentrolls WHERE StudentID = ? ORDER BY BachID";
PreparedStatement preparedStatement = con.prepareStatement(sqlqueryPastYHi);
PreparedStatement pst=con.prepareStatement(sqlqueryPastYHi);
if(!jTextFieldsearchstid.getText().isEmpty() ) {
preparedStatement.setString(1, jTextFieldsearchstid.getText());
ResultSet resultSet = preparedStatement.executeQuery();
while(resultSet.next()){
String scolaryear = resultSet.getString("BachID");
String stclass = resultSet.getString("ClassID");
String totpercent = String.valueOf(resultSet.getInt("PourcentTotal"));
String finalplace = String.valueOf(resultSet.getInt("PlaceFinale"));
String appication = resultSet.getString("Aplication");
String behavior = resultSet.getString("Conduite");
String finalaction = resultSet.getString("ActionFinale");
String pastHistTableData [] = {scolaryear, stclass, totpercent, finalplace, appication, behavior, finalaction};
DefaultTableModel tblModel = (DefaultTableModel)jTablehipastyears.getModel();
tblModel.addRow(pastHistTableData);
}
}
else{
JOptionPane.showMessageDialog(this, "Veillez taper le matricule d'un eleve svp.");
}
}catch (Exception exception){
JOptionPane.showMessageDialog(this, "erreur des donnees: " + exception.getMessage());
}
}
is there any way to solve this and clear the table before inserting new results?
DefaultTableModel tblModel = (DefaultTableModel)jTablehipastyears.getModel();
tblModel.setRowCount(0);
while (...)
{
....
tblModel.addRow(...);
}
thanks #camickr i did changed the code as follow using your methode and it worked.
if(!jTextFieldsearchstid.getText().isEmpty() ) {
preparedStatement.setString(1,
jTextFieldsearchstid.getText());
ResultSet resultSet = preparedStatement.executeQuery();
DefaultTableModel tblModel =
(DefaultTableModel)jTablehipastyears.getModel();
tblModel.setRowCount(0);
while(resultSet.next()){
String scolaryear = resultSet.getString("BachID");
String stclass = resultSet.getString("ClassID");
String totpercent =
String.valueOf(resultSet.getInt("PourcentTotal"));
String finalplace =
String.valueOf(resultSet.getInt("PlaceFinale"));
String appication =
resultSet.getString("Aplication");
String behavior = resultSet.getString("Conduite");
String finalaction =
resultSet.getString("ActionFinale");
String pastHistTableData [] = {scolaryear, stclass,
totpercent, finalplace, appication, behavior,
finalaction};
tblModel.addRow(pastHistTableData);
}

Row_Number() in MySql result value Double, but in IBM Data Studio result Int

I want result value in java is Int like in IBM Data Studio, but in my case is java generate value in double, i don't know why?, Please help to fix it!
This my java code to generate Number in table
private void polDatToTab(ResultSet rs, JTable table) throws SQLException{
String[] colHead = new String[] {"No","NIK","Nama"};
DefaultTableModel tm = new DefaultTableModel();
ResultSetMetaData rsd = rs.getMetaData();
Vector<String> nameCol = new Vector<String>();
int kolCount = rsd.getColumnCount();
for(int i=0;i<colHead.length;i++){
nameCol.add(colHead[i]);
}
Vector<Vector<Object>> data = new Vector<Vector<Object>>();
while(rs.next()){
Vector<Object> vec = new Vector<Object>();
for(int j=1;j<=kolCount;j++){
vec.add(rs.getObject(j));
}
data.add(vec);
}
tm.setDataVector(data, nameCol);
table.setModel(tm);
}
This my java code to display Table in Gui
private void srcEmp(){
String srcE = "SELECT (#ROW_NUMBER:=#ROW_NUMBER + 1) AS No_Urut,NIK,NAMA FROM PAYROLL.KARYAWAN,"
+ "(SELECT #ROW_NUMBER:=0) AS T WHERE NAMA LIKE '%"+srcRes+"%'";
DbConnect co = new DbConnect();
co.connectDB();
try {
st = co.connection.createStatement();
ResultSet ul = st.executeQuery(srcE);
polDatToTab(ul, tabResSrc);
} catch (SQLException ex) {
Logger.getLogger(ResSrc.class.getName()).log(Level.SEVERE, null, ex);
}
}
This my sql code in IBM Data Studio generate true value in int
SELECT (#ROW_NUMBER:=#ROW_NUMBER + 1) AS No_Urut,NIK,NAMA
FROM PAYROLL.KARYAWAN,(SELECT #ROW_NUMBER:=0) AS T
WHERE NAMA LIKE '%"+srcRes+"%'
This my Result in Java Gui:
and This my Result in IBM Data Studio
Your polDatToTab method isn't generic, it looks like it's designed to work only with this particular resultset. I am jumping to that conclusion because of this line
String[] colHead = new String[] {"No","NIK","Nama"};
As such, you are aware that the first column is expected to be an int. Therefore,
vec.add(rs.getInt(1));
for(int j=2; j<=kolCount; j++){
vec.add(rs.getObject(j));
}
Does the trick

sorting a JTable using getColumnClass() when connected to JDBC

I have spent a few days trying to get my JTable sorting correctly. I know the code I have to use, but cannot seem to get it for 'fit' and work into my code. I am getting the TableModel data from a database so if i call the getColumnClass() when initalising the model, I get a NullPointerException (of course), but I can't seem to get the getColumnClass(int) to work anywhere else such as model.getColumnClass(columnIndex). I only need to sort the first column in numerical order as the rest are strings. Here is my code. (ps: this is the first time using JBDC so I most likely have errors in the order I am calling - or maybe doing it in 'longhand' haha)
public JTable memberList()
{
JTable jTable1;
DefaultTableModel model;
model = new DefaultTableModel();
jTable1 = new JTable(model);
TableRowSorter sorter = new TableRowSorter(model);
try
{
Statement stmt = conn.createStatement();
String sql = "select rm.race_no,cm.firstname,cm.lastname,cm.phone,cm.dob,cm.email,cm.TwinTown_ID,rm.disqualified,cm.notes\n" +
"from competitor_master cm join competitor_season cs on cm.competitor_id = cs.competitor_id\n" +
"inner join race_master rm on cs.race_no= rm.race_no where cm.twintown_id is not null and cs.season_start_year in (year(sysdate()))\n" +
"group by (race_no);";
ResultSet rs = stmt.executeQuery(sql);
String b = "", c = "", d = "", e = "", f = "", g = "", h = "", i = "";
int a;
model.addColumn("Member Number");
model.addColumn("First Name");
model.addColumn("Last Name");
model.addColumn("Phone");
model.addColumn("Date of Birth");
model.addColumn("Email");
model.addColumn("TT Member Number");
model.addColumn("Disqualified");
model.addColumn("Notes");
while(rs.next())
{
a = rs.getInt(1);
b = rs.getString("FirstName");
c = rs.getString("LastName");
d = rs.getString("phone");
e = rs.getString("dob");
f = rs.getString("email");
g = rs.getString("TwinTown_ID");
h = rs.getString("disqualified");
i = rs.getString("notes");
model.addRow(new Object[] {a,b,c,d,e,f,g,h,i});
model.getColumnClass(1);
}
stmt.close();
rs.close();
}
catch (SQLException ex)
{
}
jTable1.getTableHeader().setFont(new Font("Microsoft Tai Le", Font.BOLD, 14));
jTable1.getTableHeader().setBackground(Color.WHITE);
jTable1.getTableHeader().setForeground(new Color(234, 168, 82));
jTable1.getTableHeader().setBorder(null);
jTable1.setRowSorter(sorter);
return jTable1;
}
public Class getColumnClass (int column){
if (column==1) {
return(Integer.class);
}
return(String.class);
}
it is sorting but by the first number only. so is sorting like this: 123 17 22 28 45 5 56 66
Because it is treating all data as String data.
model = new DefaultTableModel();
jTable1 = new JTable(model);
You are using the default implementation of the DefaultTableModel and the JTable. The default implementation of the getColumnClass(...) method just returns Object.class so the toString() value of each object is sorted.
You don't invoke the getColumnClass() method manually, you need to override the getColumnClass(...) method of your TableModel:
model = new DefaultTableModel()
{
#Override
public Class getColumnClass (int column)
{
return (column == 0) ? Integer.class : String.class;
}
};

How to show all records in database to JTable?

Excuse me. I want to show all records in JTable. But I get confused because my coding just show 1 record. When I click it again, that just show same records.
Can you help me how to get all records?
try {
Statement stmt;
stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM menu");
if (rs.next()) {
String menu_id = rs.getString("menu_id");
String menu_type = rs.getString("menu_type");
String menu_cat = rs.getString("menu_cat");
String menu_name = rs.getString("menu_name");
String menu_price = rs.getString("menu_price");
DefaultTableModel model = (DefaultTableModel) tblMenu.getModel();
model.addRow(new Object[]{menu_id, menu_type, menu_cat, menu_name, menu_price});
}
} catch (Exception e) {
System.out.println("Failed " + e);
}
I have no Idea how to code it. Thank you
Change
if (rs.next())
to
while (rs.next())
to run to the code block not just once, but till the end of the ResultSet.
It should actually look like this
DefaultTableModel model = (DefaultTableModel) tblMenu.getModel();
while (rs.next()) {
String menu_id = rs.getString("menu_id");
String menu_type = rs.getString("menu_type");
String menu_cat = rs.getString("menu_cat");
String menu_name = rs.getString("menu_name");
String menu_price = rs.getString("menu_price");
model.addRow(new Object[]{menu_id, menu_type, menu_cat, menu_name, menu_price});
}
Try this
String[] cols={"id","type","cat","name","price"};
ArrayList<String[]> list = new ArrayList<String[]>();
while (rs.next()) {
String menu_id = rs.getString("menu_id");
String menu_type = rs.getString("menu_type");
String menu_cat = rs.getString("menu_cat");
String menu_name = rs.getString("menu_name");
String menu_price = rs.getString("menu_price");
list.add(new String[]{menu_id, menu_type, menu_cat, menu_name, menu_price});
}
String[][] elts= new String[list.size()][];
elts = list.toArray(elts);
JTable table = new JTable(elts,cols);
JScrollPane pane = new JScrollPane(table, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
frame.getContentPane().add(pane);
You have used if(rs.next()) you know that if condition checked if it is true or false.
rs.next()
shifts the cursor to the next row of the result set from the database and returns true if there is any row, otherwise false. In combination with the if statement (instead of the while) this means that you expecting in only one row. simply,
rs.next()
check for next row if it is exist if condition passed and do the code block and get out from the block run the rest of the code.
As to the concrete question about iterate through the database table and add all to the jTable. You only have to change one keyword,
if to while
What happens when you use while keyword instead if keyword is that rs.next() check for next row and if it is true then condition true for while loop and go through the code block and when block is finish again check for next row. Likewise go through the all rows in your table and condition will fail after last row.

Categories