help updating database!!

Hi Gud PM

i would like to ask some question about the code below.

why is it when i click theupdate button after i add the second data it does not update the database but the first data i add can be update.

heres the code:

import javax.swing.*;

import java.awt.event.*;

import java.awt.*;

import javax.swing.event.*;

import javax.swing.table.*;

publicclass OpdrachtVriendenextends JFrame

{

JTable myTable;

JButton update;

JButton insert;

JButton delete;

JPanel p;

OpdrachtVriendenTableModel tm;

JScrollPane myPane;

OpdrachtVrienden()

{

try

{

UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");

}

catch(Exception e)

{

System.out.println("Error on look and feel");

}

update =new JButton("Update");

insert =new JButton("Add");

delete =new JButton("Delete");

p =new JPanel();

tm =new OpdrachtVriendenTableModel();

myTable =new JTable(tm);

myPane =new JScrollPane(myTable,

JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,

JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);

myTable.setSelectionForeground(Color.white);

myTable.setSelectionBackground(Color.red);

myTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);

p.add(myPane);

p.add(update);

p.add(insert);

p.add(delete);

update.addActionListener(new ActionListener()

{

publicvoid actionPerformed(ActionEvent e)

{

tm.updateDB();

}

});

insert.addActionListener(new ActionListener()

{

publicvoid actionPerformed(ActionEvent e)

{

tm.addRow();

myTable.setEditingRow(tm.getRowCount());

myTable.setRowSelectionInterval(tm.getRowCount()-1,tm.getRowCount()-1);

}

});

delete.addActionListener(new ActionListener()

{

publicvoid actionPerformed(ActionEvent e)

{

int rowToDelete = myTable.getSelectedRow();

tm.deleteRow(rowToDelete);

myTable.setEditingRow(rowToDelete -1);

myTable.setRowSelectionInterval(rowToDelete -1,rowToDelete -1);

}

});

this.addWindowListener(new WindowAdapter()

{

publicvoid windowClosing(WindowEvent e)

{

System.exit(0);

}

});// end windowlistener

this.setContentPane(p);

this.setVisible(true);

this.pack();

}// constructor

publicstaticvoid main (String args[])

{

new OpdrachtVrienden();

}// main

}//class

-

import javax.swing.table.*;

import java.sql.*;

import java.util.Vector;

publicclass OpdrachtVriendenTableModelextends AbstractTableModel

{

Connection link;

Statement statement;

ResultSet results;

int li_cols = 0;

Vector allRows;

Vector row;

Vector newRow;

Vector colNames;

String dbColNames[];

String pkValues[];

String tableName;

ResultSetMetaData myM;

String pKeyCol;

Vector deletedKeys;

Vector newRows;

boolean ibRowNew =false;

boolean ibRowInserted =false;

OpdrachtVriendenTableModel()

{

try

{

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

}

catch(ClassNotFoundException e)

{

System.out.println("Cannot Load Driver!");

}

try

{

link = DriverManager.getConnection("jdbc:odbc:Enroll","root","");

statement = link.createStatement();

results = statement.executeQuery("SELECT * FROM studentinfo");// Eventueel nog aanpassen

deletedKeys =new Vector();

newRows =new Vector();

myM = results.getMetaData();

tableName = myM.getTableName(1);

li_cols = myM.getColumnCount();

dbColNames =new String[li_cols];

for(int col = 0; col < li_cols; col ++)

{

dbColNames[col] = myM.getColumnName(col + 1);

}

allRows =new Vector();

while(results.next())

{

newRow =new Vector();

for(int i = 1; i <= li_cols; i++)

{

newRow.addElement(results.getObject(i));

}// for

allRows.addElement(newRow);

}// while

}

catch(SQLException e)

{

System.out.println(e.getMessage());

}

}

public Class getColumnClass(int col)

{

return getValueAt(0,col).getClass();

}

publicboolean isCellEditable(int row,int col)

{

if (ibRowNew)

{

returntrue;

}

if (col == 0)

{

returnfalse;

}

else

{

returntrue;

}

}

public String getColumnName(int col)

{

return dbColNames[col];

}

publicint getRowCount()

{

return allRows.size();

}

publicint getColumnCount()

{

return li_cols;

}

public Object getValueAt(int arow,int col)

{

row = (Vector) allRows.elementAt(arow);

return row.elementAt(col);

}

publicvoid setValueAt(Object aValue,int aRow,int aCol)

{

Vector dataRow = (Vector) allRows.elementAt(aRow);

dataRow.setElementAt(aValue, aCol);

fireTableCellUpdated(aRow, aCol);

}

publicvoid updateDB()

{

String updateLine[] =new String[dbColNames.length];

try

{

DatabaseMetaData dbData = link.getMetaData();

String catalog;// Get the name of all of the columns for this table

String curCol;

colNames =new Vector();

ResultSet rset1 = dbData.getColumns(null,null,tableName,null);

while (rset1.next())

{

curCol = rset1.getString(4);

colNames.addElement(curCol);

}

rset1.close();

pKeyCol = colNames.firstElement().toString();

// Go through the rows and perform INSERTS/UPDATES/DELETES

int totalrows;

totalrows = allRows.size();

String dbValues[];

Vector currentRow =new Vector();

pkValues =new String[allRows.size()];

// Get column names and values

for(int i=0;i < totalrows;i++)

{

currentRow = (Vector) allRows.elementAt(i);

int numElements = currentRow.size();

dbValues =new String[numElements];

for(int x = 0; x < numElements; x++)

{

String classType = currentRow.elementAt(x).getClass().toString();

int pos = classType.indexOf("String");

if(pos > 0)

{// we have a String

dbValues[x] ="'" + currentRow.elementAt(x) +"'";

updateLine[x] = dbColNames[x] +" = " +"'" + currentRow.elementAt(x) +"',";

if (dbColNames[x].toUpperCase().equals(pKeyCol.toUpperCase()))

{

pkValues[i] = currentRow.elementAt(x).toString() ;

}

}

pos = classType.indexOf("Integer");

if(pos > 0)// we have an Integer

{

dbValues[x] = currentRow.elementAt(x).toString();

if (dbColNames[x].toUpperCase().equals(pKeyCol.toUpperCase()))

{

pkValues[i] = currentRow.elementAt(x).toString();

}

else

{

updateLine[x] = dbColNames[x] +" = " + currentRow.elementAt(x).toString() +",";

}

}

pos = classType.indexOf("Boolean");

if(pos > 0)// we have a Boolean

{

dbValues[x] = currentRow.elementAt(x).toString();

updateLine[x] = dbColNames[x] +" = " + currentRow.elementAt(x).toString() +",";

if (dbColNames[x].toUpperCase().equals(pKeyCol.toUpperCase()))

{

pkValues[i] = currentRow.elementAt(x).toString() ;

}

}

}// For Loop

// If we are here, we have read one entire row of data. Do an UPDATE or an INSERT

int numNewRows = newRows.size();

int insertRow = 0;

boolean newRowFound;

for (int z = 0;z < numNewRows;z++)

{

insertRow = ((Integer) newRows.get(z)).intValue();

if(insertRow == i+1)

{

StringBuffer InsertSQL =new StringBuffer();

InsertSQL.append("INSERT INTO " + tableName +" (");

for(int zz=0;zz<=dbColNames.length-1;zz++)

{

if (dbColNames[zz] !=null)

{

InsertSQL.append(dbColNames[zz] +",");

}

}// Strip out last comma

InsertSQL.replace(InsertSQL.length()-1,InsertSQL.length(),")");

InsertSQL.append(" VALUES(" + pkValues[i] +",");

for(int c=1;c < dbValues.length;c++)

{

InsertSQL.append(dbValues[c] +",");

}

InsertSQL.replace(InsertSQL.length()-1,InsertSQL.length(),")");

statement.executeUpdate(InsertSQL.toString());

ibRowInserted=true;

}

}// End of INSERT Logic

// If row has not been INSERTED perform an UPDATE

if(ibRowInserted ==false)

{

StringBuffer updateSQL =new StringBuffer();

updateSQL.append("UPDATE " + tableName +" SET ");

for(int z=0;z<=updateLine.length-1;z++)

{

if (updateLine[z] !=null)

{

updateSQL.append(updateLine[z]);

}

}

// Replace the last ',' in the SQL statement with a blank. Then add WHERE clause

updateSQL.replace(updateSQL.length()-1,updateSQL.length()," ");

updateSQL.append(" WHERE " + pKeyCol +" = " + pkValues[i] );

statement.executeUpdate(updateSQL.toString());

}//for

}

}

catch(Exception ex)

{

System.out.println("SQL Error! Cannot perform SQL UPDATE " + ex.getMessage());

}

// Delete records from the DB

try

{

int numDeletes = deletedKeys.size();

String deleteSQL;

for(int i = 0; i < numDeletes;i++)

{

deleteSQL ="DELETE FROM " + tableName +" WHERE " + pKeyCol +" = " +

((Integer) deletedKeys.get(i)).toString();

System.out.println(deleteSQL);

statement.executeUpdate(deleteSQL);

}

// Assume deletes where successful. Recreate Vector holding PK Keys

deletedKeys =new Vector();

}

catch(Exception ex)

{

System.out.println(ex.getMessage());

}

}

publicvoid deleteRow(int rowToDelete)

{

// Mark row for a SQL DELETE from the Database

Vector deletedRow = (Vector) allRows.get(rowToDelete);

Integer pkKey = (Integer) deletedRow.get(0);

deletedKeys.add(pkKey);

allRows.remove(rowToDelete);

fireTableRowsDeleted(rowToDelete,rowToDelete);

}

publicvoid addRow()

{

// Mark the row for a SQL INSERT in the Database

newRows.add(new Integer(allRows.size() +1));

// Get the total number of rows in the Vector

int rowNumber = allRows.size();

int pos;

// Get what a row looks like

int numElements = newRow.size();

Vector newRowVect =new Vector();

for(int i = 0; i < numElements; i++)

{

String classType = newRow.elementAt(i).getClass().toString();

pos = classType.indexOf("String");

if(pos > 0)// we have an String

{

String blankString =new String();

newRowVect.addElement(blankString);

}

pos = classType.indexOf("Integer");

if(pos > 0)// we have a String

{

Integer blankInt =new Integer("0");

newRowVect.addElement(blankInt);

}

pos = classType.indexOf("Boolean");

if(pos > 0)// we have an Boolean

{

Boolean blankBool =new Boolean(false);

newRowVect.addElement(blankBool);

}

}

allRows.addElement(newRowVect);

ibRowNew =true;

this.isCellEditable(allRows.size(),0);

System.out.println(allRows.size());

fireTableRowsInserted(rowNumber,rowNumber);

}

}

Message was edited by:

lesbon

[22370 byte] By [lesbona] at [2007-11-27 11:09:46]
# 1

Please, please, please use PreparedStatements.

Please don't mix Swing and JDBC code in the same class.

cotton.ma at 2007-7-29 13:37:31 > top of Java-index,Java Essentials,Java Programming...
# 2

can anybody tell me whats wrong in the post code above?

and what's specific line is wrong?

thanks in advance.......

lesbona at 2007-7-29 13:37:31 > top of Java-index,Java Essentials,Java Programming...
# 3

Well your code is really very long. I doubt if someone is going to look at it until you can specify which ling is causing the problem. secondly too many nested for loops and if/else statement. May be you need to read this

http://www.sdnshare.com/view.jsp?id=525

lrngjavaa at 2007-7-29 13:37:31 > top of Java-index,Java Essentials,Java Programming...
# 4

Hi Guys

try to run the code above cause i can't find whats wrong with the code.

he...he..he...

thanks in advance..........:-D

lesbona at 2007-7-29 13:37:31 > top of Java-index,Java Essentials,Java Programming...
# 5

Hi Guys Gud PM

i try to use PreparedStatements but it does not work.......?

heee...he...:-d

lesbona at 2007-7-29 13:37:31 > top of Java-index,Java Essentials,Java Programming...
# 6

try to see this code and make some changes in your code if you want. Secondly its necessary to have a save button in your program.

import com.sun.rowset.*;

import java.net.*;

import java.sql.*;

import java.awt.*;

import java.awt.event.*;

import java.io.*;

import java.util.*;

import javax.swing.*;

import javax.sql.*;

import javax.sql.rowset.*;

/**

This program uses metadata to display arbitrary tables

in a database.

*/

public class RowSetTest

{

public static void main(String[] args)

{

JFrame frame = new RowSetFrame();

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

frame.setVisible(true);

}

}

/**

The frame that holds the data panel and the navigation

buttons.

*/

class RowSetFrame extends JFrame

{

public RowSetFrame()

{

setTitle("RowSetTest");

setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);

tableNames = new JComboBox();

tableNames.addActionListener(new

ActionListener()

{

public void actionPerformed(ActionEvent event)

{

showTable((String) tableNames.getSelectedItem());

}

});

add(tableNames, BorderLayout.NORTH);

try

{

Connection conn = getConnection();

try

{

DatabaseMetaData meta = conn.getMetaData();

ResultSet mrs = meta.getTables(null, null, null, new String[] { "TABLE" });

while (mrs.next())

tableNames.addItem(mrs.getString(3));

}

finally

{

conn.close();

}

}

catch (SQLException e)

{

JOptionPane.showMessageDialog(this, e);

}

catch (IOException e)

{

JOptionPane.showMessageDialog(this, e);

}

JPanel buttonPanel = new JPanel();

add(buttonPanel, BorderLayout.SOUTH);

previousButton = new JButton("Previous");

previousButton.addActionListener(new

ActionListener()

{

public void actionPerformed(ActionEvent event)

{

showPreviousRow();

}

});

buttonPanel.add(previousButton);

nextButton = new JButton("Next");

nextButton.addActionListener(new

ActionListener()

{

public void actionPerformed(ActionEvent event)

{

showNextRow();

}

});

buttonPanel.add(nextButton);

deleteButton = new JButton("Delete");

deleteButton.addActionListener(new

ActionListener()

{

public void actionPerformed(ActionEvent event)

{

deleteRow();

}

});

buttonPanel.add(deleteButton);

saveButton = new JButton("Save");

saveButton.addActionListener(new

ActionListener()

{

public void actionPerformed(ActionEvent event)

{

saveChanges();

}

});

buttonPanel.add(saveButton);

}

/**

Prepares the text fields for showing a new table, and

shows the first row.

@param tableName the name of the table to display

*/

public void showTable(String tableName)

{

try

{

// open connection

Connection conn = getConnection();

try

{

// get result set

Statement stat = conn.createStatement();

ResultSet result = stat.executeQuery("SELECT * FROM " + tableName);

// copy into row set

rs = new CachedRowSetImpl();

rs.setTableName(tableName);

rs.populate(result);

}

finally

{

conn.close();

}

if (scrollPane != null)

remove(scrollPane);

dataPanel = new DataPanel(rs);

scrollPane = new JScrollPane(dataPanel);

add(scrollPane, BorderLayout.CENTER);

validate();

showNextRow();

}

catch (SQLException e)

{

JOptionPane.showMessageDialog(this, e);

}

catch (IOException e)

{

JOptionPane.showMessageDialog(this, e);

}

}

/**

Moves to the previous table row.

*/

public void showPreviousRow()

{

try

{

if (rs == null || rs.isFirst()) return;

rs.previous();

dataPanel.showRow(rs);

}

catch (SQLException e)

{

System.out.println("Error " + e);

}

}

/**

Moves to the next table row.

*/

public void showNextRow()

{

try

{

if (rs == null || rs.isLast()) return;

rs.next();

dataPanel.showRow(rs);

}

catch (SQLException e)

{

JOptionPane.showMessageDialog(this, e);

}

}

/**

Deletes current table row.

*/

public void deleteRow()

{

try

{

rs.deleteRow();

if (!rs.isLast()) rs.next();

else if (!rs.isFirst()) rs.previous();

else rs = null;

dataPanel.showRow(rs);

}

catch (SQLException e)

{

JOptionPane.showMessageDialog(this, e);

}

}

/**

Saves all changes.

*/

public void saveChanges()

{

try

{

Connection conn = getConnection();

try

{

rs.acceptChanges(conn);

}

finally

{

conn.close();

}

}

catch (SQLException e)

{

JOptionPane.showMessageDialog(this, e);

}

catch (IOException e)

{

JOptionPane.showMessageDialog(this, e);

}

}

/**

Gets a connection from the properties specified

in the file database.properties

@return the database connection

*/

public static Connection getConnection()

throws SQLException, IOException

{

Properties props = new Properties();

FileInputStream in

= new FileInputStream("database.properties");

props.load(in);

in.close();

String drivers = props.getProperty("jdbc.drivers");

if (drivers != null) System.setProperty("jdbc.drivers", drivers);

String url = props.getProperty("jdbc.url");

String username = props.getProperty("jdbc.username");

String password = props.getProperty("jdbc.password");

return DriverManager.getConnection(url, username, password);

}

public static final int DEFAULT_WIDTH = 400;

public static final int DEFAULT_HEIGHT = 200;

private JButton previousButton;

private JButton nextButton;

private JButton deleteButton;

private JButton saveButton;

private DataPanel dataPanel;

private Component scrollPane;

private JComboBox tableNames;

private CachedRowSet rs;

}

/**

This panel displays the contents of a result set.

*/

class DataPanel extends JPanel

{

/**

Constructs the data panel.

@param rs the result set whose contents this panel displays

*/

public DataPanel(RowSet rs) throws SQLException

{

fields = new ArrayList<JTextField>();

setLayout(new GridBagLayout());

GridBagConstraints gbc = new GridBagConstraints();

gbc.gridwidth = 1;

gbc.gridheight = 1;

ResultSetMetaData rsmd = rs.getMetaData();

for (int i = 1; i <= rsmd.getColumnCount(); i++)

{

gbc.gridy = i - 1;

String columnName = rsmd.getColumnLabel(i);

gbc.gridx = 0;

gbc.anchor = GridBagConstraints.EAST;

add(new JLabel(columnName), gbc);

int columnWidth = rsmd.getColumnDisplaySize(i);

JTextField tb = new JTextField(columnWidth);

fields.add(tb);

gbc.gridx = 1;

gbc.anchor = GridBagConstraints.WEST;

add(tb, gbc);

}

}

/**

Shows a database row by populating all text fields

with the column values.

*/

public void showRow(ResultSet rs) throws SQLException

{

for (int i = 1; i <= fields.size(); i++)

{

String field = rs.getString(i);

JTextField tb = (JTextField) fields.get(i - 1);

tb.setText(field);

}

}

private ArrayList<JTextField> fields;

}

lrngjavaa at 2007-7-29 13:37:31 > top of Java-index,Java Essentials,Java Programming...
# 7

?-:P

lesbona at 2007-7-29 13:37:31 > top of Java-index,Java Essentials,Java Programming...
# 8

does not help...

but thanks in advance.....

lesbona at 2007-7-29 13:37:31 > top of Java-index,Java Essentials,Java Programming...