AboutArtemus Harper Expertise I have a BS in computer science and am working towards a Masters degree.
Experience I have experience in Core Java, good background in Java swing/gui, some experience with JNI, Java reflection, and Java java.nio.*
knowledge of Java bytecode and annotations.
Basics in c++ and c#
Question QUESTION: i want to edit the cells in JTable which takes its data from a MS-Access database and those edits should get saved in the database.i defined the setValueAt ,getValueAt IN TABLEMODEL and have made a class implementing TableModelListener and called that in the main class (main class containing the jtable).i am able to change the values in cell but the values are not being saved on clicking of a button "update" .
PLEASE HELP ME AS SOON AS POSSIBLE.
ANSWER: In your Connection object (assuming you are using the java.sql package) you would first turn off auto commit in the Connection interface, e.g. con.setAutoCommit(false). Then you any changes made should be done though the updateXXX method in ResultSet. When you want to save the changes you can call commit() in the Connection interface, or if you want to revert you can call rollback().
There is no reason to have a table listener if you are already implementing the setValueAt method.
---------- FOLLOW-UP ----------
QUESTION: thanks so much i will try to implement it bt cn u provide a sample code for it please its really urgent i ve been stuck at it since a month...ill be highly thankful to you..
ANSWER: Not having too much skill with databases, I've made up a simple example of what you want... you can see the code here: http://rafb.net/p/8lL21z90.html
There are two classes there, a main, which I used to create the table and connect to the database, you will need to modify this to your database specifications (do make sure you turn auto commit off though). Note that no updates are made to the database until the button is pressed.
The second is a model for the JTable that handles the display and update. This is pretty simple, and you may not like how some objects like dates are handled.
---------- FOLLOW-UP ----------
QUESTION: this is my code one is the jdbctablemodel
and the other is trhe main one in which i m making my gui and displaying the jtable.
whenever i change the values in the cells it throws exception "SQL syntax error and COUNT error"
public void executeQuery()
{
int i,max;
Vector rowData;
int curType;
try
{
data = new Vector();
names = new Vector();
resultSet = statement.executeQuery(queryStr);
metaData = resultSet.getMetaData();
max = metaData.getColumnCount();
//get the column names
for(i=0;i<max;i++)
{
//adjust for meta data index start at 1
names.addElement(metaData.getColumnLabel(i+1));
}
//load the data
while (resultSet.next())
{
rowData = new Vector();
for (i=0;i<max;i++)
{
rowData.addElement(resultSet.getObject(i+1));
}
data.addElement(rowData);
}
fireTableChanged(null);
}
catch (Exception exp)
{
System.out.println("Error performing query: "+exp);
exp.printStackTrace();
}
}
public void executeDelete(int row)
{
if(row > -1)
{
// Get the product ID.
Object id = this.getValueAt(row,0);
if(statement != null)
{
try
{
/*
Set the value of the first paramter in
this compiled delete statement.
*/
delStatement.setObject(1,id);
// Execute the statement.
delStatement.executeUpdate();
//Refresh. In JDBC 2.0, there is a refresh method.
this.executeQuery();
}catch(SQLException e)
{
System.out.println(e);
return;
}
}
}
}
public void setValueAt(Object value, int row, int col)
{
Vector rowData = (Vector)data.elementAt(row);
Object o = dataRow.elementAt(col);
if(o! = value)
{
try
{
String s = "UPDATE Table2 SET " +
metaData.getColumnName(col+1) + "=";
int curType = metaData.getColumnType(col+1);
switch(curType)
{
case Types.CHAR:
case Types.VARCHAR:
case Types.LONGVARCHAR:
case Types.DATE:
s += ""+value.toString()+"";
break;
case Types.TINYINT:
case Types.SMALLINT:
case Types.INTEGER:
case Types.BIGINT:
case Types.FLOAT:
case Types.DOUBLE:
s += value.toString();
break;
default:
s += ""+value.toString()+"";
}
s += " WHERE CUSTID = " + dataRow.elementAt(0)+"";
statement.executeUpdate(s);
// refresh
this.executeQuery();
connection.commit();
public String getColumnName(int col)
{
String retVal;
retVal = (String) names.elementAt(col);
if(retVal == null)
retVal = "";
return retVal;
}
public boolean isCellEditable(int row, int col)
{ return true; }
/*public void setValueAt(Object value, int row, int col)
{
Vector dataRow = (Vector) data.elementAt(row);
dataRow.setElementAt(value, col);
fireTableCellUpdated(row, col);
}*/
public int getColumnCount()
{
return names.size();
}
public int getRowCount()
{
return data.size();
}
public Object getValueAt(int row, int col)
{
Vector rowData = (Vector)data.elementAt(row);
return rowData.elementAt(col);
}
}
and this is the main class in which i m creating that jtable
here u'll see one button "btn"
this is my SECOND QUESTION :
i have one column custid in my table "Table2"
and i ve a label CUSTID and textfield(corrsponding to it) in my gui .so i want that whenever i type a custid in that textfield only those rows having that id should get displayed in jtable.. i ve tried to do that with set value method but execptions are coming.. what to do i m lost
//initializing textfields
tf1 = new JTextField(12);
tf2 = new JTextField(12);
tf3 = new JTextField(12);
tf4 = new JTextField(12);
tf6 = new JTextField(12);
lblname = new JLabel("Customer Name");
lblid = new JLabel("Cust Id");
lbldate=new JLabel("Date");
lblitemid=new JLabel("ItemId");
lblp=new JLabel("Price");
lblmsg = new JLabel("",JLabel.CENTER);
//initializing panels
p1 = new JPanel();
p2 = new JPanel();
p3 = new JPanel();
psouth = new JPanel();
//connection object created using DriverManager class
//swati is the name of the database
Connection connect =DriverManager.getConnection("jdbc:odbc:swati");
//creating prepared statement object pstm so that query can be
//sent to database
pstm=connect.prepareStatement("insert into Table2 values(?,?,?,?)");
pstm.setString(1,tf2.getText());
pstm.setString(2,tf6.getText());
pstm.setString(3,tf3.getText());
pstm.setString(4,tf4.getText());
//execute method to execute the query
pstm.executeUpdate();
lblmsg.setText("Details have been added to database");
//closing the prepared statement and connection object
pstm.close();
connect.close();
}
catch(SQLException sqe)
{
System.out.println("SQl error");
}
catch(ClassNotFoundException cnf)
{
System.out.println("Class not found error");
}
}
if(e.getSource()==btnexit)
{
System.exit(0);
}
Answer For your first question, I can't really help with that since I don't have your database (or even Access). You should print out the query that you are executing before executing and manually ensure that it is valid.
As for the second question, you could keep a map of the rows you are showing in the table along with the index they have in the query in order to make the correct update. Or you could just create a new query to update the item based on the key of the row (e.g. the custid), remember as long as autocommit is turrned off, you can update when ever a change is made, and only call commit when the user presses the update button.
Also... please do not concatenate strings when forming queries. You never know when a ' might appear in an entry and screw up things. Use the prepared query with the ?. You currently do this in the setValueAt method.