Java ResultSet SQL with GUI - java

I'm having a strange problem with the below code, it works fine when its run without the if else statements, but displays no results in the jtable when if else is used. Is there something stupid I'm missing here?
try {
Class.forName(dbClass);
Connection con = DriverManager.getConnection (dbUrl,dbUsername, dbPassword);
Statement stmt = con.createStatement();
String userQuery = "SELECT p_id AS 'Patient ID', forename AS 'Forename', surname AS 'Surname', address AS 'Address' FROM Patient WHERE surname LIKE '%"+s+"%'";
ResultSet userResult = stmt.executeQuery(userQuery);
if(!userResult.next())
{
JOptionPane.showMessageDialog(null, "No Results.");
{
else{
ResultSetMetaData rsMetaData =userResult.getMetaData();
DefaultTableModel dtm = new DefaultTableModel();
int cols = rsMetaData.getColumnCount();
Vector colName = new Vector();
Vector dataRows = new Vector();
for (int i=1; i<cols; i++){
colName.addElement(rsMetaData.getColumnName(i));
}
dtm.setColumnIdentifiers(colName);
while(userResult.next()){
dataRows = new Vector();
for(int j = 1; j<cols; j++){
dataRows.addElement(userResult.getString(j));
}
dtm.addRow(dataRows);
}
searchTable.setModel(dtm);
con.close();
}
} //end try
catch(ClassNotFoundException e) {
JOptionPane.showMessageDialog(null, "Database Error.");
e.printStackTrace();
}
catch(SQLException e) {
JOptionPane.showMessageDialog(null, "Database Error.");
e.printStackTrace();
}
I'm using netbeans for the GUI.
Thanks

The connection object (con) should be closed outside if/else block.
Beside, the userResult.next() was called twice in the else statement block..
You may fix it by replacing while() by do while loop:
do {
dataRows = new Vector();
for (int j = 1; j < cols; j++) {
dataRows.addElement(userResult.getString(j));
}
dtm.addRow(dataRows);
}
while (userResult.next());

Please include finally to handle closing the connection and removing the other resources.

Related

how to sort a table from database

I want to be able to sort a table from the database, according to either the quatity or the name, but how do i decided what happens in what case?
Below is the code for the table.
public void tableupdate(JTable jTable1, String fill) {
try {
try {
Class.forName("org.h2.Driver");
Connection con = DriverManager.getConnection("jdbc:h2:file:D:/Inventory.db", "sa", "");
Statement stat = con.createStatement();
fill = "SELECT * FROM BOOKDESC ";
ResultSet rs = stat.executeQuery(fill);
while (jTable1.getRowCount() > 0) {
((DefaultTableModel) jTable1.getModel()).removeRow(0);
}
int columns = rs.getMetaData().getColumnCount();
while (rs.next()) {
Object[] row = new Object[columns];
for (int i = 1; i <= columns; i++) {
row[i - 1] = rs.getObject(i);
}
((DefaultTableModel) jTable1.getModel()).insertRow(rs.getRow() - 1, row);
}
rs.close();
stat.close();
con.close();
} catch (ClassNotFoundException e) {
JOptionPane.showMessageDialog(null, e);
}
} catch (SQLException e) {
JOptionPane.showMessageDialog(null, e);
}
}
MySQL is offering a method for sorting data in your SELECT statement, it's called ORDER BY.
Usage is found here.
This way, your code doesn't have to do the work, as your ResultSet already gets sorted data.

get more rows in JTable java

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 need to fix my update to the dynamic jTable by a search in my Access database

I have a problem in updating my single jtable from Microsoft Access Database.
I do not have any error messages. I tried out the Query for the database using like, but my jtable does not populate in relation to the data stored in the database.
public TableModel setAuthorSearchEjournalTableValues(){
String eJournalAuthor = jTextField30.getText();
ResultSet tableData = DCE.searchEjournalbyAuthor(eJournalAuthor);
try {
ResultSetMetaData md = tableData.getMetaData();
int columnCount = md.getColumnCount();
Vector columns = new Vector(columnCount);
for (int i = 1; i <= columnCount; i++) {
columns.add(md.getColumnName(i));
}
Vector data = new Vector();
Vector row;
while (tableData.next()) {
row = new Vector(columnCount);
for (int i = 1; i <= columnCount; i++) {
row.addElement( tableData.getString(i) );
}
data.add(row);
}
DefaultTableModel tableModel = new DefaultTableModel(data, columns);
return tableModel;
//Debugging
} catch (SQLException ex) {
ex.printStackTrace();
}
return null;
}`
And my result retrieving query is here
public ResultSet searchEjournalbyAuthor(String author){
conn = Connect();
try{
String myQuery = "select AuthorDetails,Year,Titleofarticle,Journaltitle,volume,pagenumbers,URL,AccessedDate from Ejournalcitation where AuthorDetails = '"+author+"'";
pst = conn.prepareStatement(myQuery);
rs = pst.executeQuery();
return rs;
}catch(SQLException ex){
ex.printStackTrace();
}
return null;
}
with the code to display as
private void jTextField30KeyReleased(java.awt.event.KeyEvent evt) {
// TODO add your handling code here:
if(jComboBox1.getSelectedIndex()==0&&jComboBox2.getSelectedIndex()==0){//BookTitle
jTable1.setModel(setTitleSearchBookTableValues());
}
else if(jComboBox1.getSelectedIndex()==0&&jComboBox2.getSelectedIndex()==1){//BookAuthor
jTable1.setModel(setAuthorSearchBookTableValues());
}
else if(jComboBox1.getSelectedIndex()==1&&jComboBox2.getSelectedIndex()==0){//WebSiteTitle
jTable1.setModel(setTitleSearchWebSiteTableValues());
}
else if(jComboBox1.getSelectedIndex()==1&&jComboBox2.getSelectedIndex()==1){//WebSiteAuthor
jTable1.setModel(setAuthorSearchWebSiteTableValues());
}
else if(jComboBox1.getSelectedIndex()==2&&jComboBox2.getSelectedIndex()==0){//Ejournaltitle
jTable1.setModel(setTitleSearchEjournalTableValues());
}
else if(jComboBox1.getSelectedIndex()==3&&jComboBox2.getSelectedIndex()==1){//EjournalAuthor
jTable1.setModel(setAuthorSearchEjournalTableValues());
}
else{
JOptionPane.showMessageDialog(null, "Please enter a value and select the type of search");
}
}
Help me out!! Thanks in advance
you must include
DefaultTableModel tableModel = (DefaultTableModel) jTable1.getModel();
tableModel.fireTableDataChanged();
with the corrected query
String myQuery = "select AuthorDetails,Year,Titleofarticle,Journaltitle,volume,pagenumbers,URL,AccessedDate from Ejournalcitation where AuthorDetails like '%"+author+"%'";

SELECT statement in JAVA

public void search() throws Exception{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
String url = "jdbc:odbc:******";
String user = "*****";
String pass = "*****";
Connection con = DriverManager.getConnection(url, user, pass);
Statement state = con.createStatement();
ResultSet rs = state.executeQuery("");
ResultSetMetaData rsmetadata = rs.getMetaData();
int columns = rsmetadata.getColumnCount();
DefaultTableModel dtm = new DefaultTableModel();
Vector column_name = new Vector();
Vector data_rows = new Vector();
for (int i=1; i<columns;i++){
column_name.addElement(rsmetadata.getColumnName(i));
}
dtm.setColumnIdentifiers(column_name);
while(rs.next()){
data_rows = new Vector();
for (int j=1; j<columns; j++){
data_rows.addElement(rs.getString(j));
}
dtm.addRow(data_rows);
}
tblPatient.setModel(dtm);
}
On my ResultSet rs = state.executeQuery() I used this SQL
"SELECT "
+ "pIDNo AS 'Patient ID',"
+ "pLName AS 'Last Name',"
+ "pFName AS 'First Name',"
+ "pMI AS 'M.I.',"
+ "pSex AS 'Sex',"
+ "pStatus AS 'Status',"
+ "pTelNo AS 'Contact No.',"
+ "pDocID AS 'Doctor ID',"
+ "pAddr AS 'St. No.',"
+ "pStreet AS 'St. Name',"
+ "pBarangay AS 'Barangay',"
+ "pCity AS 'City',"
+ " pProvince AS 'Province',"
+ " pLNameKIN AS 'Last Name',"
+ "pFNameKIN AS 'First Name',"
+ "pMIKIN AS 'M.I.',"
+ "pRelationKIN AS 'Relation',"
+ "pTotalDue AS 'Total Due'"
+ " FROM dbo.Patients");
First I run this line (pTotalDue didn't come up to jTable.)
And on my second attempt to display it I do this:
"SELECT pTotalDue AS 'Total Due' FROM dbo.Patients"
Now I tried this one, and I think something's really wrong about my codes. BTW this column has MONEY DATA TYPE
why does it didn't show to my JTable? could anyone tell me what is the problem with my codes?
(Problem in the answer that has given to me)
public class QueryOnWorkerThread extends SwingWorker{
private final JTable tableToUpdate;
public QueryOnWorkerThread( JTable aTableToUpdate ) {
tableToUpdate = aTableToUpdate;
}
#Override
protected TableModel doInBackground() throws Exception {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
String url = "jdbc:odbc:OJT_dsn";
String user = "sa";
String pass = "";
Connection con = DriverManager.getConnection( url, user, pass );
Statement state = con.createStatement();
ResultSet rs = state.executeQuery("");
ResultSetMetaData rsmetadata = rs.getMetaData();
int columns = rsmetadata.getColumnCount();
DefaultTableModel dtm = new DefaultTableModel();
Vector column_name = new Vector();
Vector data_rows;
//note the <= check iso the < check (as the count starts at index 1)
for (int i=1; i<=columns;i++){
column_name.addElement(rsmetadata.getColumnName(i));
}
dtm.setColumnIdentifiers(column_name);
while(rs.next()){
data_rows = new Vector();
//note the <= check iso the < check (as the count starts at index 1)
for (int j=1; j<=columns; j++){
data_rows.addElement(rs.getString(j));
}
dtm.addRow(data_rows);
}
return dtm;
}
`#Override <<<<<<<<<<<<<<<<<<<<< I have a problem here it says : done() in javaapplication25.SearchPatient.QueryWorkerThread cannot override done() in javax.swing.SwingWorker overriden method does not throw java.lang.Exception , what does it mean sir?`
protected void done() throws Exception{
//this method runs on the EDT, so it is safe to update our table here
try {
tableToUpdate.setModel( get() );
} catch ( InterruptedException e ) {
throw new RuntimeException( e );
} catch ( ExecutionException e ) {
throw new RuntimeException( e );
}
}
try this
DefaultTableModel dtm=(DefaultTableModel)table.getModel();
for (int i = dtm.getRowCount() - 1; i > -1; i--) {
dtm.removeRow(i);
}
Connection con = DriverManager.getConnection(url, user, pass);
Statement state = con.createStatement();
ResultSet rs = state.executeQuery("Your SQL Query");
while(rs.next())
{
String str1=rs.getString(1);
String str2=rs.getString(2);
String str3=rs.getString(3);
String str4=rs.getString(4);
String str5=rs.getString(5);
:
:
:
dtm.addRow(new Object[]{str1,str2,str3,str4,str5});
}
In you loops, your exit condition is
j<columns
this means thant the last column will never be recovered. try this insted:
for (int j=1; j<=columns; j++)
The fact that your last column does not appear is probably related to your loop statements, as already indicated by #Joan.
There are however more issues with this code. You should only update Swing components on the Event Dispatch Thread, and on that Thread you should not perform long running operations. In short, mixing SQL queries and updates of the JTable should not happen on the same thread. Consult the Concurrency in Swing guide for more info.
Using a SwingWorker could solve this issue:
public class QueryOnWorkerThread extends SwingWorker<TableModel, Void>{
private final JTable tableToUpdate;
public QueryOnWorkerThread( JTable aTableToUpdate ) {
tableToUpdate = aTableToUpdate;
}
#Override
protected TableModel doInBackground() throws Exception {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
String url = "jdbc:odbc:******";
String user = "*****";
String pass = "*****";
Connection con = DriverManager.getConnection( url, user, pass );
Statement state = con.createStatement();
ResultSet rs = state.executeQuery("");
ResultSetMetaData rsmetadata = rs.getMetaData();
int columns = rsmetadata.getColumnCount();
DefaultTableModel dtm = new DefaultTableModel();
Vector column_name = new Vector();
Vector data_rows;
//note the <= check iso the < check (as the count starts at index 1)
for (int i=1; i<=columns;i++){
column_name.addElement(rsmetadata.getColumnName(i));
}
dtm.setColumnIdentifiers(column_name);
while(rs.next()){
data_rows = new Vector();
//note the <= check iso the < check (as the count starts at index 1)
for (int j=1; j<=columns; j++){
data_rows.addElement(rs.getString(j));
}
dtm.addRow(data_rows);
}
return dtm;
}
#Override
protected void done() {
//this method runs on the EDT, so it is safe to update our table here
try {
tableToUpdate.setModel( get() );
} catch ( InterruptedException e ) {
throw new RuntimeException( e );
} catch ( ExecutionException e ) {
throw new RuntimeException( e );
}
}
}
The SwingWorker can be started by calling
QueryOnWorkerThread worker = new QueryOnWorkerThread( tblPatient );
worker.execute();
Note how I changed the loops in your code
Try getting that column via ResultSet.getBigDecimal() rather than via ResultSet.getString(). Then put your retrieved BigDecimal.toPlainString() into your table cell.
Example:
data_rows.addElement(rs.getBigDecimal("pTotalDue").toPlainString());//Assuming your select returns a pTotalDue Column (e.g. SELECT pTotalDue,... FROM ...)
Try to Use an TableCellRenderer.
Implement the Renderer and render the Column with the Money Type in the form you wish.
Regards,
HL

Unable to display all the rows in my netbeans jtable from sql

I want to display all 5 columns of my SQL database table bk_det in my jtable which is in netbeans ide in java language but I am only able to display 4 columns instead of 5. What is the problem can any one help m posting the code below:
private void btviewbkdetActionPerformed(java.awt.event.ActionEvent evt) {
if(evt.getSource()==btviewbkdet){
try {
DBUtil util = new DBUtil();
Connection con = util.getConnection();
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("select * from bk_det");
ResultSetMetaData rsmetadata = rs.getMetaData();
int columns = rsmetadata.getColumnCount();
DefaultTableModel dtm = new DefaultTableModel();
Vector columns_name = new Vector();
Vector data_rows = new Vector();
for(int i=1; i< columns; i++){
columns_name.addElement(rsmetadata.getColumnName(i));
}
dtm.setColumnIdentifiers(columns_name);
while(rs.next()){
data_rows = new Vector();
for(int j=1; j< columns; j++){
data_rows.addElement(rs.getString(j));
}
dtm.addRow(data_rows);
}
tblbnkdet.setModel(dtm);
} catch (Exception ex) {
JOptionPane.showMessageDialog(null, ex.getMessage());
Logger.getLogger(Demo.class.getName()).log(Level.SEVERE, null, ex);
} // TODO add your handling code here:
}
}
private void btbkrepviewActionPerformed(java.awt.event.ActionEvent evt) {
if(evt.getSource()==btviewbkdet){
try {
DBUtil util = new DBUtil();
Connection con = util.getConnection();
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("select * from dbo.bk_rep");
ResultSetMetaData rsmetadata = rs.getMetaData();
int columns = rsmetadata.getColumnCount();
DefaultTableModel dtm = new DefaultTableModel();
Vector columns_name = new Vector();
Vector data_rows = new Vector();
for(int i=1; i< columns; i++){
columns_name.addElement(rsmetadata.getColumnName(i));
}
dtm.setColumnIdentifiers(columns_name);
while(rs.next()){
data_rows = new Vector();
for(int j=1; j< columns; j++){
data_rows.addElement(rs.getString(j));
}
dtm.addRow(data_rows);
}
tblbkrep.setModel(dtm);
} catch (Exception ex) {
JOptionPane.showMessageDialog(null, ex.getMessage());
Logger.getLogger(Demo.class.getName()).log(Level.SEVERE, null, ex);
} // TODO add your handling code here:
} // TODO add your handling code here:
}
Here is the change
for(int i=1; i<= columns; i++){
columns_name.addElement(rsmetadata.getColumnName(i));
}

Categories