How to remove data in database from jTable? - java

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.

Related

How do I subtract an input from jtextfield to mysql database?

How do i subract an input from mysql database?
Let's say I'm doing a bill and inventory system. So when the user input a quantity on a jtextfield, it'd minus off from the table.
will attach the GUI.
right now, i have written this method
public boolean updateBill(Bill bi) {
boolean success = false;
dbController db = new dbController();
PreparedStatement ps;
try {
myConn = DriverManager.getConnection("jdbc:mysql://localhost:3306/ooadp?useSSL=false", "root", "pass");
Statement myStatement = myConn.createStatement();
String sql = "UPDATE medicalproduct SET quantity = quantity - ? WHERE productID = ?, productName = ?, dosage = ?, price = ?, status = ?" ;
myStatement.executeUpdate(sql);
myConn.close();
} catch (Exception e) {
e.printStackTrace();
}
return success;
}
but then I do not know what to write on my actionPerform and how to link my jtextfield to the sql query.
This is how my gui looks like
Your sql statement is invalid anyway... But if am right, all you want to do is subtract from a field in the database by the value specified in a jTextField
//For example quantity -= txtfieldValue;
If does what you want. You can query for the value of the field, do the subtraction and then finally update the field. Here is an example for updating only the quantity:
public void updateQuantity(String txtFieldValue,String id) throws ClassNotFoundException, SQLException{
Class.forName("com.mysql.jdbc.Driver");
System.out.println("Driver loaded!!!");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/ooadp?useSSL=false", "root", "pass");
System.out.println("Connection created!!!");
PreparedStatement pState;
String sqlRawP1 ="select quantity from medicalproduct where productID=?";//I guess medicalproduct is your table name
pState = conn.prepareStatement(sqlRawP1);
pState.setString(1, id);
ResultSet rSetQuantity = pState.executeQuery();
int countQuantity = 0;
while(rSetQuantity.next()){
countQuantity = rSetQuantity.getInt(1);//Am assumming that quantity is an integer
}
int value = Interger.parseInt(txtFieldValue);
countQuantity-= value;
String sqlRawP2 = "update medicalproduct set quantity=? where productID=?";
pState = conn.prepareStatement(sqlRawP2);
pState.setInt(1,countQuantity);
pState.setString(2, id);
pState.executeUpdate();
}
Hope it will work well..Forgive me if there are minor errors because I haven't tested it myself.

Insert sql query not inserting row in db

I am inserting a new row in db, there is no exception in the console. But the row is not inserted into the table.
String name = request.getParameter("name");
String city = request.getParameter("city");
String country = request.getParameter("country");
String query = "INSERT INTO `test`.`student`(Name,City,Country)VALUES(?,?,?);";
PreparedStatement ps = (PreparedStatement) con.prepareStatement(query);
ps.setString(1,name);
ps.setString(2,city);
ps.setString(3,country);
ps.executeUpdate();
ps.close();
No need of casting the PreparedStatement again in connecting the query. It should be like
Connection conn = getDBConnection();
PreparedStatement ps = con.prepareStatement(query);
Remove the ; from the query inside the doublequotes
Prefer concatenation operator ( + sign) while using single quotes inside double quoted strings in the query
Here is a sample code that I have tested and working fine. Compare it with your code to know what you are doing wrong.
public void insertRowToDB(int staffID, String first_name, String last_name, int department_ID) {
Connection dbConnection = null;
try {
dbConnection = DatabaseConnection.getconnection();
if (!dbConnection.isClosed()) {
String sql = "INSERT INTO staff (staffID,first_name,last_name,department_ID) VALUES(?,?,?,?)";
PreparedStatement statement = dbConnection.prepareStatement(sql);
statement.setInt(1, staffID);
statement.setString(2, first_name);
statement.setString(3, last_name);
statement.setInt(4, department_ID);
statement.executeUpdate();
}
} catch (SQLException ex) {
Logger.getLogger(DatabaseConnection.class.getName()).log(Level.SEVERE, null, ex);
} finally {
try {
if (dbConnection!=null) {
if (!dbConnection.isClosed()) {
dbConnection.close();
}
}
} catch (SQLException ex) {
Logger.getLogger(DatabaseConnection.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
A priori view of your code, there is no the commit statement.
You need to perform this statement right before the ps.close() line.
Best regards!

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.

MySQL table values in JComboBox

I designed a swing interface with MySQL table. I put two comboboxes in a manner when the 1st combobox value is selected (Brand Name), the second combobox values (available items under thise selected brand) will be loaded via a mysql query. My code is...
try{
String url = "jdbc:mysql://localhost:3306/databasename";
String login = "root"; String password = ""; Connection con = DriverManager.getConnection(url, login, password);
try{
comboBox1 = new JComboBox(); comboBox1.setEditable(false);
comboBox1.addItem("- - -");
Statement stmt1=null;
String query1 = "SELECT brand FROM brands";
stmt1 = con.createStatement();
ResultSet rs1 = stmt1.executeQuery(query1);
while(rs1.next()) {comboBox1.addItem(rs1.getString(1));}
comboBox2 = new JComboBox(); comboBox2.setEditable(false);
comboBox1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event){
String comboBox1Selected=comboBox1.getSelectedItem().toString();
try{
Statement stmt2=null;
String query2 = "SELECT item FROM "+comboBox1Selected+"";
stmt2 = con.createStatement();
ResultSet rs2 = stmt2.executeQuery(query2);
while(rs2.next()) {comboBox2.addItem(rs2.getString(1));}
}
catch (SQLException ex1) {JOptionPane.showMessageDialog(null,"Failed to Item-List..!"); ex1.printStackTrace(); return;}
}
});
}
catch (SQLException ex2) {JOptionPane.showMessageDialog(null,"Failed to Brand-List..!"); ex2.printStackTrace(); return;}
}
catch (SQLException ex3) {ex3.printStackTrace(); JOptionPane.showMessageDialog(null,"Unable to Connect..!"); return;}
The problem is, eventhough the comboboxes are functioning correctly, if I select another choice from 1st combobox, the second combobox doesn't avoid the "older values" (they appears with the newer values).
What might be the reason..? Anyone could explain..?
Thanks in advance.
Call comboBox2.removeAllItems() before adding the new items here while(rs2.next()) {comboBox2.addItem(rs2.getString(1));}

Updating database from a dynamic jtable

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

Categories