Hello everyone!
I have a button on my main form that allows me to get the visitInfo Table. The data are displayed inside a JTable.
What I would like to know is how do I edit or delete a row from that Jtable by the click of a save button or delete button.
Here is the class that shows the JTable with the Save, delete and Exit Buttons.
/*This class shows the result of the visit information
* related to a specific type of service.
* When the user select a service type and
* click on the Get visitInfo Button.
*/
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.*;
import java.util.*;
import javax.swing.*;
import javax.swing.JPanel;
import javax.swing.table.DefaultTableModel;
public class VisitTable extends JFrame
{
//Specifies the driver name
String driver = "sun.jdbc.odbc.JdbcOdbcDriver";
// specifies the location of the database in which the table resides
String url = "JDBC:ODBC:Student";
//No userid nor password is required to access the database
String userid = "";
String password = "";
//Connection,statement and resulset are all set to null for now
Connection connection =null;
Statement stmt = null;
ResultSet rs = null;
JTable visittable;
DefaultTableModel model;
Vector columnNames;
Vector visitdata ;
JButton SaveBtn,DelBtn,ExitBtn;
//constructor
public VisitTable(Object selectedItem){
super("Visit Information");
columnNames = new Vector();
visitdata = new Vector();
/*SQL query that retrieves all the visit information
* about a specific type of visit
chosen by the user from a combobox*/
String query = "SELECT * FROM VisitTable WHERE TypeofService='"+ selectedItem+"'";
try{
// Connect to the Database
Class.forName(driver);
connection = DriverManager.getConnection( url, userid, password );
// Read data from a table
stmt = connection.createStatement();
rs = stmt.executeQuery(query);
ResultSetMetaData md = rs.getMetaData();
//Get number of columns
int columns = md.getColumnCount();
// Get column names
for (int i = 1; i <= columns; i++){
columnNames.addElement( md.getColumnName(i) );
}
// Get row data
while ((rs!= null)&&(rs.next())){
Vector row = new Vector(columns);
for (int i = 1; i <= columns; i++){
row.addElement( rs.getObject(i) );
}
visitdata.addElement( row );
}
//Close the resultset, statement and the connection
rs.close();
connection.close();
stmt.close();
}catch(Exception e){
System.out.println( e );
}
// Create table with data queried from the table "VisitTable"
visittable = new JTable(visitdata, columnNames);
model = new DefaultTableModel(visitdata,columnNames);
model.insertRow(visittable.getRowCount(),new Object[] {"","","","",""});
JScrollPane scrollPane = new JScrollPane( visittable );
JPanel BtnPanel = new JPanel();
// This method add new record to the table
SaveBtn = new JButton("Save Row");
SaveBtn.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
}
});
//This method remove the selected row from the table
DelBtn = new JButton("Delete Row");
DelBtn.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
}
});
//This method close the Visit Information frame
ExitBtn = new JButton("Exit");
ExitBtn.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
}
});
//Add the buttons to the GUI
BtnPanel.add(SaveBtn);
BtnPanel.add(DelBtn);
BtnPanel.add(ExitBtn);
Container c =getContentPane();
c.setLayout(new FlowLayout(FlowLayout.CENTER,20,20));
c.add(scrollPane);
c.add(BtnPanel);
}
} Please I'd be very grateful to recieve a help on this.
Thanks for the support!
You need to pass at the constructor of the JTable as parameter the DefaultTableModel. Check the API of JTable.
Then use the methods of DefaultTableModel to add, remove, or update the rows. Check the API of DefaultTableModel.
please follow the suggestion of javaAddict ..
and check API for DefaultTableModel ..
DefaultTableModel model =
(DefaultTableModel)someTable.getModel();
model.removeRow(rowIndex);You need to pass at the constructor of the JTable as parameter the DefaultTableModel.
but as you can see the constructor has already got a parameter, the selected item from the comboBox and that is important for the table to display the result.
please follow the suggestion of javaAddict .. and check API for DefaultTableModel ..
DefaultTableModel model = (DefaultTableModel)someTable.getModel(); model.removeRow(rowIndex);
Hello musthafa!
Please help on this , I didn't get what JavaAddict meant.
Can you materialize the words by some snippets?
Thank you!
i think you need delete row at the same time you need to save deleted roe as some file...
alright..
try to see this link and get some idea..
if you can go ahead..
else reply what trick you need...
http://www.roseindia.net/java/example/java/swing/RemoveRows.shtml
Hello musthafa! Please help on this , I didn't get what JavaAddict meant. Can you materialize the words by some snippets? Thank you!
Did you look at the JTable API? There is a constructor that takes as argument TableModel. That is how you will instantiate your JTable. You already have the DefaultTableModel. Just use this as argument
And read their APIs. All the methods you need are right there.
Did you look at the JTable API? There is a constructor that takes as argument TableModel. That is how you will instantiate your JTable. You already have the DefaultTableModel. Just use this as argument And read their APIs. All the methods you need are right there.
Yeah I read some
here is for the delete button what I've done, but the prob is it removes the row from the Jtable but not from the datadase table.
//This method remove the selected row from the table
DelBtn = new JButton("Delete Row");
DelBtn.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
try{
model.removeRow(visittable.getSelectedRow());
}catch(Exception ex){
ex.printStackTrace();
}
}
}); Here is what you meant by usng the defaultTablemodel as constructor, right?
model = new DefaultTableModel(visitdata,columnNames);
visittable = new JTable(model); But for the save button I have no clues!
Yeah I read some here is for the delete button what I've done, but the prob is it removes the row from the Jtable but not from the datadase table.
Because you need to run a query to do that. And try to put it in a separate method, in a separate class that takes only arguments.
At the save row, what do you want to do? Because there are methods that can make the cells of the table editable, so you can change their values.
And then, when you click "Save", just take the selected Row, use the API to take the values of the cell and call a query at the database
Because you need to run a query to do that. And try to put it in a separate method, in a separate class that takes only arguments.
At the save row, what do you want to do? Because there are methods that can make the cells of the table editable, so you can change their values. And then, when you click "Save", just take the selected Row, use the API to take the values of the cell and call a query at the database
Here is what I've done. Any help on this
// This method add new record to the table
SaveBtn = new JButton("Save Row");
SaveBtn.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
int rs2 = 0;
try{
String query ="INSERT INTO VisitTable VALUES('"+visittable.getSelectedRow()+"')";
Connection cn2 = DriverManager.getConnection(url, userid, password);
Statement st2 = cn2.createStatement();
rs2 = st2.executeUpdate(query);
}catch(Exception ex){
ex.printStackTrace();
}
}
});
//This method remove the selected row from the table
DelBtn = new JButton("Delete Row");
DelBtn.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
try{
model.removeRow(visittable.getSelectedRow());
}catch(Exception ex){
ex.printStackTrace();
}
}
});
Please help!
What errors do you get?
Did you look at the API for the JTable to see what the getSeletectedRow does?
Why aren't you closing the Connection, Statement? How many times do I have to tell you that?
I already told you that you need to call a query to delete the row form the database as well. Didn't you read that?
Why aren't you using separate methods for the database operations. Do you find it easier to repeat code every time you want to insert or delete something:
public void delete(int id) throws SQLException {
// commands
} All the Connections, ... will be declared in that method.
public void delete(int id) throws SQLException { // commands }All the Connections, ... will be declared in that method.
I don't think you get what I want to do?
I want to select and delete a row from JTable and reflect it on the database , how can I write tha sql statement. should it be[CODE]DELETE * FROM TableName [CODE]
Do I have to specify a where clause?
If yes please help on how I could write that.
Thanks!
I don't think you get what I want to do? I want to select and delete a row from JTable and reflect it on the database , how can I write tha sql statement. should it be [CODE]DELETE * FROM TableName [CODE] Do I have to specify a where clause? If yes please help on how I could write that.
Thanks!
if you have 2 button for add and delete...
when you call add make connection to DB AND make a query to add data in DB AND JTABLE(YOU KNOW HOW DO ADD) IN
actionprformed_add
{
//db connection (better to write once a time using utility calss no need to make connection for every call )
//and query
//add data in jtable
}
actionprformed_delete
{
///write delete qury
//delete record from jtable
}
this is what yo need to do...
what difficulties you have now...
I don't think you get what I want to do? I want to select and delete a row from JTable and reflect it on the database , how can I write tha sql statement. should it be [CODE]DELETE * FROM TableName [CODE] Do I have to specify a where clause? If yes please help on how I could write that.
Thanks!
If you don't know sql you should have said that. You can search the web to find the syntax of the delete command. Then when you select the row use the JTable API to get the values of the row. You should have a primary key that you can use at the where clause. That needs to be taken from the JTable.
For the rest, I told you were and how to call it
If you don't know sql you should have said that. You can search the web to find the syntax of the delete command. Then when you select the row use the JTable API to get the values of the row. You should have a primary key that you can use at the where clause. That needs to be taken from the JTable.
For the rest, I told you were and how to call it
Try examinig this please!
import java.sql.*;
public class VisitMethods {
public VisitMethods( ){
try {
}catch (Exception ex) {
ex.printStackTrace();
}
try{
}catch(Exception ex){
ex.printStackTrace();
}
}
public void delete(String id) throws SQLException {
Connection cn = null;
Statement st = null;
String q = "DELETE * FROM VisitTable WHERE PatientNo='"+id+"'";
String user= "";
String pass = "";
String url = "JDBC:ODBC:Student";
String driver = "sun.jdbc.odbc.JdbcOdbcDriver";
try{
Class.forName(driver);
cn = DriverManager.getConnection(url, user, pass);
st = cn.createStatement();
st.executeUpdate(q);
}catch(Exception e){
e.printStackTrace();
}
finally{
if(cn!=null) cn.close();
if(st!=null) st.close();
}
}
public void save(String Pno) throws SQLException{
Connection cn1 = null;
Statement st1 = null;
String q = "INSERT INTO PatientTable VALUES('"+ Pno + "')";
String user= "";
String pass = "";
String url = "JDBC:ODBC:Student";
String driver = "sun.jdbc.odbc.JdbcOdbcDriver";
try{
Class.forName(driver);
cn1 = DriverManager.getConnection(url, user, pass);
st1 = cn1.createStatement();
st1.executeUpdate(q);
}catch(Exception e){
e.printStackTrace();
}
finally{
if(cn1!=null) cn1.close();
if(st1!=null) st1.close();
}
}
} I did this but how could I call this in the buttons' actionPerformed methods?
Thanks for the support!
That is how it's done. Also at your insert query. Does that table have only one column? You might get errors on that query if the table PatientTable has more columns.
Also about how to call them.
I did this but how could I call this in the buttons' actionPerformed methods?
I am sorry to tell you this, but you don't know how to call a method, and you are trying to create a gui that connects to the database?
No wonder that you couldn't understand anything I was telling you.
I am not saying this to put you down. It's the truth. Everybody would agree with me.
Calling a method is the most basic thing. You have written all this code and you don't know that? That proves you shouldn't be doing this.
Stop what you are doing and start over. Learn how to create objects instantiate them, use their methods. Try small exercises.
Given the amount of information you received it should have been a piece of cake to finish this. You have been given anything you need to finish this. All the advices and all the code that you couldn't find by yourself.
Now if you can't do this, it would be because you haven't studied what is needed.
Given your last question made me doubt that you even understand what the code you have written does or that you understood the code I gave you. There were many times that you just copied my code and then after a lot of questions I again told you how to change it; something you should have done by yourself.
I am willing to continue helping, but you must first make some progress on your own
I am sorry to tell you this, but you don't know how to call a method, and you are trying to create a gui that connects to the database? No wonder that you couldn't understand anything I was telling you. I am not saying this to put you down. It's the truth. Everybody would agree with me.
Don't be sorry at all! you know I've learned alot since we started exchangin on this site. I said how could I call those in the buttons' actionPerformed methods, I know how to call a method but right now I am just trying to finish this project cause my future depends on it. Have you ever been an intern in a company that gives you things you've never done before and expect you to provide in a short time?
I told you since my first post on this site that I'm a beginer who happens to be forced to develop something he's never done before, so please be understanding and help me out on what i've done.
and yes my table has 5 cols.
Thanks for your understanding!
PS: I did this already but it is not working, so I wanted to see how you as a much more experienced than me could've made it work.
// This method add new record to the table
SaveBtn = new JButton("Save Row");
SaveBtn.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
try{
VisitMethods savmthd = new VisitMethods();
savmthd.save(""+visittable.getSelectedRow());
model.fireTableRowsInserted(0, visittable.getSelectedRow()+1);
}catch(Exception ex){
ex.printStackTrace();
}
}
});
//This method remove the selected row from the table
DelBtn = new JButton("Delete Row");
DelBtn.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
try{
model.removeRow(visittable.getSelectedRow());
VisitMethods delmthd = new VisitMethods();
delmthd.delete(""+visittable.getSelectedRow());
model.fireTableRowsDeleted(0, visittable.getSelectedRow()+1);
}catch(Exception ex){
ex.printStackTrace();
}
}
});
Once again thanks!
Anyone help please !
I am dying here.
public void delete(String id) throws SQLException {
Connection cn = null;
Statement st = null;
String q = "DELETE * FROM VisitTable WHERE PatientNo='"+id+"'";
String user= "";
String pass = "";
String url = "JDBC:ODBC:Student";
String driver = "sun.jdbc.odbc.JdbcOdbcDriver";
try{
Class.forName(driver);
cn = DriverManager.getConnection(url, user, pass);
st = cn.createStatement();
st.executeUpdate(q);
}catch(Exception e){
e.printStackTrace();
}
finally{
if(cn!=null) cn.close();
if(st!=null) st.close();
}
}
public void save(visit vInfo) throws SQLException{
Connection cn1 = null;
String q = "INSERT INTO VisitTable VALUES(?,?,?,?,?)";
String user= "";
String pass = "";
String url = "JDBC:ODBC:Student";
String driver = "sun.jdbc.odbc.JdbcOdbcDriver";
try{
Class.forName(driver);
cn1 = DriverManager.getConnection(url, user, pass);
PreparedStatement ps = cn1.prepareStatement(q) ;
ps.setString(1, vInfo.getPatientNo());
ps.setString(2, vInfo.getID());
ps.setString(3, vInfo.getFirst());
ps.setString(4, vInfo.getSub());
ps.setString(5, vInfo.getType());
ps.executeUpdate();
}catch(Exception e){
e.printStackTrace();
}
finally{
if(cn1!=null) cn1.close();
}
} And call them here:
// This method add new record to the table from the JTable
SaveBtn = new JButton("Save Row");
SaveBtn.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
try{
visit vInfo = new visit(visittable.getSelectedRow());
VisitMethods savmthd = new VisitMethods();
savmthd.save(vInfo);
model.fireTableRowsUpdated(0, visittable.getSelectedRow()+1);
}catch(Exception ex){
ex.printStackTrace();
}
}
});
//This method remove the selected row from the table
DelBtn = new JButton("Delete Row");
DelBtn.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
try{
model.removeRow(visittable.getSelectedRow());
VisitMethods delmthd = new VisitMethods();
delmthd.delete(""+visittable.getSelectedRow());
model.fireTableRowsDeleted(0, visittable.getSelectedRow()+1);
}catch(Exception ex){
ex.printStackTrace();
}
}
}); here is the visit class
[public class visit{
private String Pno ="";
private String Idnum="";
private String frst ="";
private String sub ="";
private String tpos ="";
public visit(int selectedRow) {
try{
visit();
}catch(Exception e){
System.err.println("Exception"+e.getMessage());
e.printStackTrace();
}
}
public String [] visit(){
String [] rows = {this.Pno, this.Idnum, this.frst, this.sub, this.tpos};
return rows;
}
// Set Values
public void setPatientNo(String Pn){
Pno=Pn;
}
public void setID(String id){
Idnum=id;
}
public void setFirst(String fs){
frst=fs;
}
public void setSub(String sb){
sub=sb;
}
public void setType(String typ){
tpos = typ;
}
//Get the Values
public String getPatientNo(){
return Pno;
}
public String getID(){
return Idnum;
}
public String getFirst(){
return frst;
}
public String getSub(){
return sub;
}
public String getType(){
return tpos;
}
}
When I run and execute the save action it gives me this exception
java.sql.SQLException: General error
at sun.jdbc.odbc.JdbcOdbc.createSQLException(JdbcOdbc.java:6986)
at sun.jdbc.odbc.JdbcOdbc.standardError(JdbcOdbc.java:7114)
at sun.jdbc.odbc.JdbcOdbc.SQLExecute(JdbcOdbc.java:3149)
at sun.jdbc.odbc.JdbcOdbcPreparedStatement.execute(JdbcOdbcPreparedStatement.java:216)
at sun.jdbc.odbc.JdbcOdbcPreparedStatement.executeUpdate(JdbcOdbcPreparedStatement.java:138)
at VisitMethods.save(VisitMethods.java:59)
<pre><code>ps.executeUpdate();</code></pre>
at VisitTable$1.actionPerformed(VisitTable.java:89)
<pre><code>savmthd.save(vInfo);</code></pre>
Please daniweb members, save my life!
Thanks in advance for your concern!
Have you tried printing the query to see what do you run.
About the delete method:
I will repeat myself once again. Read the JTable API. Are you sure that the getSelectedRow is what you need to pass as argument? What your query takes as argument and what the getSelectedRow returns.
Have you tried printing the query to see what do you run.
It still gives the exception with this SQL statement
INSERT INTO VisitTable VALUES(?,?,?,?,?) And regarding the delete the button I wrote this
model.removeRow(visittable.getSelectedRow());
VisitMethods delmthd = new VisitMethods();
delmthd.delete(" "+visittable.getSelectedRow());
in the try block.
I don't get cause I've read the API but can't figure out any other method.
PS: the delete button remove the row from the JTable but not from the database table.
Thanks!