Updating database from a dynamic jtable - java

I am trying to update a database from a dynamic JTable. Here is my code
try {
//open connection...
conn = javaConnect.ConnectDb();
//select the qualifications table row for the selected staffID
String sql2 = "select * from QualificationsTable where qualID =" + theRowID;
pStmt = conn.prepareStatement(sql2);
ResultSet rs2 = pStmt.executeQuery();
//check if QualificationsTable has content on that row...
if (rs2.next()) {
//it has content update...
//get the model for the qual table...
DefaultTableModel tModel = (DefaultTableModel) qualTable.getModel();
for (int i = 0; i < tModel.getRowCount(); i++) {
//get inputs from the tables
String qualification = tModel.getValueAt(i, 0).toString();
String yearAttained = tModel.getValueAt(i, 1).toString();
//sql query for updating qualifications table...
String sql3 = "update QualificationsTable set qualifications = ?, yearAttained = ? where qualID = ?";
pStmt = conn.prepareStatement(sql3);
//set the pareameters...
pStmt.setString(1, qualification);
pStmt.setString(2, yearAttained);
pStmt.setInt(3, theRowID);
//execute the prepared statement...
pStmt.execute();
// dbStatement.executeUpdate("INSERT INTO tableName VALUES('"+item+"','"+quant+"','"+unit+"','"+tot+"')");
}
//close connection
conn.close();
JOptionPane.showMessageDialog(null, "Qualifications updated successfully!", "Success", INFORMATION_MESSAGE);
} else {
//it doesnt have content insert...
//get the model for the qual table...
DefaultTableModel tModel = (DefaultTableModel) qualTable.getModel();
for (int i = 0; i < tModel.getRowCount(); i++) {
//System.out.println(tModel.getSelectedColumn()+tModel.getSelectedRow());
//get inputs from the tables
String qualification = tModel.getValueAt(i, 0).toString();
String yearAttained = tModel.getValueAt(i, 1).toString();
//sql query for storing into QualificationsTable
String sql3 = "insert into QualificationsTable (qualifications,yearAttained,qualID) "
+ "values (?,?,?)";
pStmt = conn.prepareStatement(sql3);
//set the parameters...
pStmt.setString(1, qualification);
pStmt.setString(2, yearAttained);
pStmt.setInt(3, theRowID);
//execute the prepared statement...
pStmt.execute();
}
//close connection
conn.close();
JOptionPane.showMessageDialog(null, "Qualifications saved successfully!", "Success", INFORMATION_MESSAGE);
}
} catch (SQLException ex) {
Logger.getLogger(StoreInfo.class.getName()).log(Level.SEVERE, null, ex);
} catch(NullPointerException nfe){
JOptionPane.showMessageDialog(infoParentTab, "Please, always hit the Enter button to effect your changes on the table", "USER ERROR!", ERROR_MESSAGE);
}
} else {
JOptionPane.showMessageDialog(infoParentTab, "You must select a Staff from the Browser...", "USER ERROR!", ERROR_MESSAGE);
}
} catch (SQLException e) {
JOptionPane.showMessageDialog(null, e);
e.printStackTrace();
}
what i am actually trying to do is to use a table linked to a database to store qualifications of staff in a company. now each entry in the qualifications database is referenced to the staffID in the staffs database through qualID.
so when i store the qualification on the table, it also records the staff that has the qualification. this should enable me retrieve a particular staff's qualifications from the database when need.
the segment for inserting into the database if empty works fine (i.e. the else... segment). but the update segment (i.e. the if... segment) is faulty in the sense that the code uses the last row on the JTable to populate all the rows in the database table instead of replicating all the new changes into the database table when update is need.
i have tried everything i could to no avail. please i need much help in this...time is not on my side. tnx guys in advance

The best way to do this is to use a CachedRowSet to back up the JTable's model. You'll be able to view, insert and update data easily.
Here's the tutorial: Using JDBC with GUI API

Related

Update one column from table and insert new rows. sqlite, java

I have some problems to modify data from a table.
I need to update an entire column from a specific table and if there's no sufficient rows I need to insert more.
More exactly, the user will be able to modify data from interface, in a text area that contains current data from db.
I put all the text in a list, each line representing an element of the list.
In a certain column, I must go through each row and modify it with a list item. If there are more lines in the text area than number of rows in that table, I need to insert new ones, which will contain the remaining items from the list.
I would be grateful if someone could give me some help.
Thanks!
#FXML
public void modify() throws SQLException {
String col= selectNorme.getValue().toString();
String text=texta.getText();
List<String> l1notes= new ArrayList<>( Arrays.asList( text.split("\r\n|\r|\n") ));
Statement stmt=null;
String client = this.clientCombobox.getValue().toString();
String tab1Client= client+ "_" +this.selectLang1.getValue().toString();
String query="SELECT * FROM "+tab1Client+" WHERE ["+ selectNorme.getValue().toString()+ "]= "+col+"";
String sqlUpdate1= "UPDATE ["+tab1Client+"] SET ["+ this.selectNorme.getValue().toString() +"] = ?";
try {
Connection conn = dbConnection.getConnection();
PreparedStatement modif=conn.prepareStatement(sqlUpdate1);
int i=0;
if (rss.next()) {
stmt = conn.createStatement();
rss = stmt.executeQuery(query);
stmt.executeUpdate(sqlUpdate1);
modif.setString(1, l1notes.get(i));
i++;
modif.execute();
}
else {
PreparedStatement pstmt = conn.prepareStatement("INSERT INTO ["+this.clientCombobox.getValue().toString()+"_"+this.selectLang1.getValue().toString()+"] (["+ this.selectNorme.getValue().toString() +"]) values (?)" );
for (int row=i; row< l1notes.size(); row++)
{
pstmt.setString(1, l1notes.get(row));
pstmt.executeUpdate();
}
}
}
finally {
try {
if (conn !=null)
conn.close();
}
catch (SQLException se){
se.printStackTrace();
}
}
}

How to remove data in database from jTable?

I want to remove the data in database from jtable. I have 1 jTextField and 1 jButton. So when i click this selected row in table, the primary key wont set in my jTextField.
Is it possible to remove the data in database from jtable without jTextField and just a button?
Heres my code
try {
int row = table.getSelectedRow();
String id_ = (table.getModel().getValueAt(row, 1)).toString();
String sql ="SELECT id FROM 'mycredentials.sales' WHERE id= "+id_+"'";
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/mycredentials?autoReconnect=true&useSSL=false", username, password);
PreparedStatement pst = (PreparedStatement) connection.prepareStatement(sql);
ResultSet rs = pst.executeQuery();
while (rs.next()) {
jFrame_removeP.setText(rs.getString("id"));
}
} catch (SQLException e1) {
System.err.println(e1);
}
Random id number appears in my jTextField. And my table code is:
String name = jFrame_pName.getText().trim();
String price = jFrame_pPrice.getText().trim();
String quantity = jFrame_quantity.getText().trim();
String total = jFrame_total.getText().trim();
String st[] = {name, price, quantity, total};
model.addRow(st);
jFrame_gTotal.setText(Integer.toString(getSum()));
try {
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/mycredentials?autoReconnect=true&useSSL=false", username, password);
Statement s = (Statement) connection.createStatement();
String sql = "INSERT INTO mycredentials.sales (name, price, quantity, total) VALUES ('"+jFrame_pName.getText()+"', '" + jFrame_pPrice.getText() + "','"+jFrame_quantity.getText()+"','"+jFrame_total.getText()+"')";
s.executeUpdate(sql);
} catch (SQLException e1) {
System.err.println(e1);
}
And my remove button is:
DefaultTableModel model1 = (DefaultTableModel) table_1.getModel();
int selectedRowIndex = table_1.getSelectedRow();
model1.removeRow(selectedRowIndex);
try {
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/mycredentials?autoReconnect=true&useSSL=false", username, password);
Statement ps = (Statement) connection.createStatement();
String sql = "DELETE from mycredentials.sales where id ='" + jFrame_removeP.getText() + "'";
ps.executeUpdate(sql);
} catch (Exception ex) {
System.err.println(ex);
}
Do you mean like this? I didn't get exactly what you needed. Hope this helps.
private void deleteBtnActionPerformed(java.awt.event.ActionEvent evt) {
String deleteQuery = "DELETE FROM SAMPLE WHERE USER_ID = ?";
try (Connection myCon = DBUtilities.getConnection(DBType.JDBC);
PreparedStatement myPs = myCon.prepareStatement(deleteQuery);){
myPs.setInt(1,userID);
myPs.executeUpdate();
JOptionPane.showMessageDialog(null,"Records deleted");
}//end of try
catch (SQLException ex) {
DBUtilities.processException(ex);
}//end of catch
}
After search a record. You just click a record in the Jtable you want to delete. And just hit the Delete Button simple as that.
Just use a refresh method here if you want to remove the selected row. Fix your statement much better if you use Prepared Statement than Statements to avoid SQL injection.

Inserting data from a database into a jTable in netbeans

I'm trying to put data from my database into a jTable and the program isn't throwing an error, but it does nothing. This is the method I'm using. Thanks for the help.
public void displayTable()
{
try
{
Connection con = DriverManager.getConnection("jdbc:ucanaccess://TransactionTrackerDB.accdb");
Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
String SQL = "SELECT transactionID, startDate, description, totalSum,"
+ " instalments, balanceDue FROM RecurringExpense ORDER BY transactionID DESC";
ResultSet rs = stmt.executeQuery(SQL);
display.setModel(DbUtils.resultSetToTableModel(rs));
}
catch (SQLException ex)
{
Logger.getLogger(MonthlyExpensesClass.class.getName()).log(Level.SEVERE, null, ex);
}
}
To put data from database into a jTable I always use user specified method such as below;
Note - I'm not including getting connection with the database codes. list_table is the table that you want to show database content.
private void updateTable(){
try {
//getting data from the mysql database
String sql = "SELECT transactionID, startDate, description, totalSum,"
+ " instalments, balanceDue FROM RecurringExpense ORDER BY transactionID DESC";
PreparedStatement pst=conn.prepareStatement(sql);
ResultSet rs=pst.executeQuery();
list_table.setModel(DbUtils.resultSetToTableModel(rs));
// re sizing the column width
list_table.getColumnModel().getColumn(0).setPreferredWidth(15);
//as this change getColumn(column number) and size the columns
} catch (Exception ex) {
JOptionPane.showMessageDialog(null, "Error : "+ex);
}
}
Then call the defined updateTable(); as you want to retrieve data from the database.

How to add data in columns in MySQL but some strings are already set?

I'm creating a program where I should save data on database. I have two frames but only using one table in one database and on the first frame I already saved data on row 1-6. Now on the second frame I want to add data on row 7-12 only. How can I do this? Or should I make another table instead?
I'm newbie to Java, so help would be great.
Here's my code for the save:
JOptionPane.showMessageDialog(this, "Save this input?", "Confirm", JOptionPane.QUESTION_MESSAGE);
strCountry = txtCountry.getText();
strMembers = txtareaMembers.getText();
strSong = txtSong.getText();
strAlbum = txtAlbum.getText();
Concert = (String) cmbConcerts.getSelectedItem();
Biblio = (String) cmbBiblio.getSelectedItem();
btnSubFirst.setEnabled(false);
btnSubPrev.setEnabled(false);
btnSubNext.setEnabled(true);
btnSubLast.setEnabled(true);
btnSubEdit.setEnabled(false);
btnSubSave.setEnabled(false);
btnSubCancel.setEnabled(true);
txtCountry.setEditable(false);
txtSong.setEditable(false);
txtAlbum.setEditable(false);
SaveData();
public void SaveData() {
try {
String strQuery = "INSERT INTO tblband(bandname,label,genre,year,member,album,country,members,song,recent,concert,biblio)" + "VALUES" + "(?,?,?,?,?,?,?,?,?,?,?,?)";
PreparedStatement st = null;
Class.forName("com.mysql.jdbc.Driver").newInstance();
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/banddb", "root", "");
st = con.prepareStatement(strQuery);
st.setString(1, strBand);
st.setString(2, strRecord);
st.setString(3, Genre);
st.setString(4, Year);
st.setString(5, Member);
st.setString(6, Album);
st.setString(7, strCountry);
st.setString(8, strSong);
st.setString(9, strAlbum);
st.setString(10, Concert);
st.setString(11, Biblio);
st.setString(12, strMembers);
st.executeUpdate();
con.close();
JOptionPane.showMessageDialog(null, "Data is successfully inserted into database.");
} catch(Exception e) {
JOptionPane.showMessageDialog(null, "Error in submitting data." + e);
}
}
You could use an update query:
The UPDATE statement is used to update existing records in a table.
UPDATE table_name
SET column1=value1,column2=value2,...
WHERE some_column=some_value;
A working example of this can be found: here.
Notice the WHERE clause in the SQL UPDATE statement!
The WHERE clause specifies which record or records that should be updated. If you omit the WHERE clause, all records will be updated!

Deleting selected row in MySQL database through JTable

tb_records = jtable name
records = table name inside my database
Date = my first column
hey = substitute for my real password
mydatabase = name of my database
My problem is that, when I highlight a row in my JTable and delete it, it deletes all the rows. I want to delete the selected row only. Here's my code:
int row = tb_records.getSelectedRow();
DefaultTableModel model= (DefaultTableModel)tb_records.getModel();
String selected = model.getValueAt(row, 0).toString();
if (row >= 0) {
model.removeRow(row);
try {
Connection conn = (Connection) DriverManager.getConnection("jdbc:mysql://localhost:3306/mydatabase", "root", "hey");
PreparedStatement ps = conn.prepareStatement("delete from records where Date='"+selected+"' ");
ps.executeUpdate();
}
catch (Exception w) {
JOptionPane.showMessageDialog(this, "Connection Error!");
}
}
What could be the problem here? How can I delete a selected row in my database and not all the rows?
DefaultTableModel model = (DefaultTableModel) jTable.getModel();
int row = jTable.getSelectedRow();
String eve = jTable.getModel().getValueAt(row, 0).
String delRow = "delete from user where id="+eve;
try {
ps = myCon.getConnection().prepareStatement(delRow);
ps.execute();
JOptionPane.showMessageDialog(null, "Congratulation !!");
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e.getMessage());
}
1) Don't display your own message. Display the error message from the Exception as it will give a better explanation what the problem is.
2) Use a proper PreparedStatement for the SQL. You are less likely to make syntax errors. Something like:
String sql = "delete from records where Date= ?";
PreparedStatement stmt = connection.prepareStatement(sql);
stmt.setString( 1, selected );
stmt.executeUpdate();
I don't know much about SQL but maybe you need to pass a Date object not a String object since your where clause is using a Date?
The OP wrote:
SOLUTION: Pick a column with unique values. My Date column has the same values that's why it's deleting all my rows even though I set my row as getSelectedRow. Time_in = my 4th column with unique values.
change
String selected = model.getValueAt(row, 0).toString();
to
String selected = model.getValueAt(row, 3).toString();
and
PreparedStatement ps = conn.prepareStatement("delete from records where Date='"+selected+"' ");
to
PreparedStatement ps = conn.prepareStatement("delete from records where Time_in='"+selected+"' ");

Categories