I have a JTable bound to MySQL. I already have done code to insert data.
But i don't know how to delete.
I have this sample delete method that works in other simple projects.
public String deleteItem(String name) {
String answer = "";
try {
Connection con = Connect.getConnection();
String sql = "Delete FROM item where name = ?";
PreparedStatement ps = con.prepareStatement(sql);
ps.setString(1, name);
ps.executeUpdate();
ps.close();
con.close();
answer = "OK";
} catch (Exception e) {
answer = e.toString();
}
return answer;
}
Even when I worked with an unbound table I have done this remove row from jtable that did well for me.
But now its a table bound to MySQL and I can't find a way to delete row... already searched on the internet. Found nothing.
PS: i'm using netbeans. i right-clicked jtable > bind > elements , to bind table.
Oh, I found a way!
First, I changed my deleteItem method, to delete by id
ItemDAO.java
public String deleteItem(int ID_item) {
String answer = "";
try {
Connection con = Connect.getConnection();
String sql = "Delete FROM item where ID_Item = ?";
PreparedStatement ps = con.prepareStatement(sql);
ps.setInt(1, ID_item);
ps.executeUpdate();
ps.close();
con.close();
answer = "OK";
} catch (Exception e) {
answer = e.toString();
}
return answer;
}
Then the action in delete button goes like this.
Form.java
private void btnDeleteActionPerformed(java.awt.event.ActionEvent evt) {
int column = 0; // get the first column which is ID_Item
int row = tableItem.getSelectedRow(); //get row selected by user
int value = (int) tableItem.getModel().getValueAt(row, column); // store ID_Item value
String answer = new ItemDAO().deleteItem(value); // call up deleteItem method
if(answer.equals("OK")) {
System.out.println("OK"); // just for test
itemList.clear(); // this is needed to update the bound table after Insert/Delete/Update etc
itemList.addAll(itemQuery.getResultList()); // same as above comment
}else{
System.out.println("ERROR"); // just for test.
}
Maybe isn't the most beautiful way to do it, but it works.
Related
int d1;
String attribute = comboBox1.getSelectedItem().toString(); // a combo box
System.out.println(attribute);
String data = t.getText(); // a textfield
System.out.println(data);
if (attribute.equals("COURSE_ID")) {
IsNumber in = new IsNumber();
d1 = in.stringToInt(data);
try {
Connection connection = DriverManager.getConnection(url, username, password);
System.out.println("connection success!!");
String sql = "DELETE FROM course WHERE ? = ?";
PreparedStatement statement = connection.prepareStatement(sql);
statement.setString(1, attribute);
statement.setInt(2, d1);
boolean rows = statement.execute();
if (rows == true) {
new ViewDatabase(user, name, pswrd);
System.out.println("COURSE_ID UNIT UPDATE SUCCESSFUL!");
frame.setVisible(false);
} else if (rows == false) {
JOptionPane.showMessageDialog(null, "Cannot find row!",
"ERROR", JOptionPane.ERROR_MESSAGE);
}
statement.close();
connection.close();
} catch (SQLException e) {
System.out.println("& i oop");
e.printStackTrace();
}
For this piece of code, whenever I try to run it, it returns "Data truncation: Truncated incorrect DOUBLE value: 'COURSE_ID'". I'm not sure what this is referring to and I searched and found some people saying that this error message is misleading, though I only found answers to selects, inserts, and updates, but not deletes.
I also turned off strict mode in MySQL, as advised from the internet, but to no avail.
You can't bind strings to actual column names in a prepared statement. So, the attribute column names must be hard-coded. One pattern which might work would be:
String sql = "";
if ("COL1".equals(attribute)) {
sql = "DELETE FROM course WHERE COL1 = ?";
}
else if ("COL2".equals(attribute)) {
sql = "DELETE FROM course WHERE COL2 = ?";
}
else {
sql = "DELETE FROM course WHERE COL3 = ?";
}
PreparedStatement statement = connection.prepareStatement(sql);
statement.setInt(1, d1);
boolean rows = statement.execute();
I'm just trying to make some combo box with value from database and I can choose it and insert it to database, but I had some error message. How to resolve that?
Here my code:
private void btnInputDataProdukActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
String sql = "insert into tb_produk (produk_kat_id,produk_nm,produk_gndre,produk_size,produk_hrg) values (?,?,?,?,?)";
try {
PreparedStatement stat = conn.prepareStatement(sql);
stat.setString(1, txtNamaProduk.toString());
String valueKat = cbKatProduk.getSelectedItem().toString();
stat.setString(2, valueKat);
String valueGender = cbGender.getSelectedItem().toString();
stat.setString(3, valueGender);
stat.setString(4, txtUkuran.toString());
stat.setString(5, txtHarga.toString());
stat.executeUpdate();
JOptionPane.showMessageDialog(null, "Data Berhasil Disimpan");
kosong();
dataTable();
lebarKolom();
txtNamaProduk.requestFocus();
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "Data Gagal Disimpan" + e);
}
}
The combo box with value from DB
public void tampil_combo(){
String sql = "select kat_id from tb_kategori";
try {
java.sql.Statement stat = conn.createStatement();
ResultSet res = stat.executeQuery(sql);
while (res.next()) {
Object[] ob = new Object[3];
ob[0]=res.getString(1);
cbKatProduk.addItem((String) ob[0]);
}
res.close();stat.close();
} catch (Exception e) {
System.err.println(e.getMessage());
}
}
produkt_kat_id is defined as an int in your database. But with
stat.setString(1, txtNamaProduk.toString());
you are setting a string. Also note that you are calling toString() on the combo box and not the selected value.
So you need to convert the selected value into an integer:
stat.setString(1, Integer.parseInt(txtNamaProduk.getSelectedItem()));
You would still need to add some error handling in case txtNamaProduk.getSelectedItem() returns null or in case the combo box can also contain other values than integers.
You will also need to change your code for the other fields that are defined as integers in the database.
Here's my code for the addStudent:
#FXML
private void addStudent(ActionEvent event) {
// sql query to insert data into students at ID, first name, last name, email and DOB
String sqlInsert = "INSERT INTO students(id,fname,lname,email,DOB) VALUES (?,?,?,?,?)";
try {
Connection conn = dbConnection.getConnection();
PreparedStatement stmt = conn.prepareStatement(sqlInsert);
// add the data in the right column
stmt.setString(1, this.id.getText());
stmt.setString(2, this.firstname.getText());
stmt.setString(3, this.lastname.getText());
stmt.setString(4, this.email.getText());
stmt.setString(5, this.dob.getEditor().getText());
stmt.execute();
conn.close();
} catch(SQLException ex) {
ex.printStackTrace();
}
}
And here's my code for removeStudent:
#FXML
private void removeStudent(ActionEvent event) {
try {
// sql query to delete data from the database
String sqlRemove = "DELETE FROM students WHERE id = ?";
// open a connection to the database and use PreparedStatement to
// initialize the query.
Connection conn = dbConnection.getConnection();
PreparedStatement delete = conn.prepareStatement(sqlRemove);
// information needed to delete the row
delete.setString(1, selectStudent());
// execute and delete
delete.executeUpdate();
// close the connection
conn.close();
} catch (SQLException ex) {
ex.printStackTrace();
}
// update table after deleting
loadStudentData(event);
}
The picture above is the view of my table. I hit LoadData and my table values show up. I want to be able to click on a row(student) and hit Delete Student to remove it.
Helper method for removeStudent:
private String selectStudent() {
String result = "";
try {
String sqlSelect = "SELECT id FROM students";
Connection conn = dbConnection.getConnection();
ResultSet rs = conn.createStatement().executeQuery(sqlSelect);
result = rs.getString(1);
conn.close();
} catch (SQLException ex) {
ex.printStackTrace();
}
return result;
}
I'm pretty sure it has to do with when I "click" on a row, the id value for that isn't being held anywhere so when I hit "Delete" nothing is being given for it to Delete.
I don't know. Any advice would be awesome. :D
First edit: nothing is assigned to delete.setString(1, this.id.getText()). When I click on the row and hit delete, nothing is happening because there's nothing being assigned to id when I click on the row. The query string DOES work however when I physically give it an ID to delete. Also verified that the button does work; it prints out a lovely message for me with a good ol' System.out.println("expletive");
Second edit: Ok, so I updated the removeStudent code and now all I get is the string "null" returned. Nothing deletes. Nothing updates. Nothing is happening except I get "null" in the console.
Third edit: Getting closer! With the realization that the removeStudent isn't being given an ID to delete, I decided to create a private helper method that will do a SELECT query. Now, when I hit delete, it'll delete....but from the top, and not at where I want it selected. The code is above.
Fourth edit: Getting even closer! So, I figured out how to capture the row I click on within the table and I can delete......however, because of my sqlRemove command, I'm deleting by id so if I click on a row with index 3, then ONLY the row within the table that has an id of 3 will be deleted, nothing else. I gotta re-write how the sqlRemove command is worded.
I fixed it:
private String selectStudent() {
// initial value for result to return
String result = "";
// grab the index of the row selected on the table
int initial = studenttable.getSelectionModel().getSelectedIndex();
try {
// SELECT query to execute
String sqlSelect = "SELECT id FROM students";
Connection conn = dbConnection.getConnection();
ResultSet rs = conn.createStatement().executeQuery(sqlSelect);
// while there's a next row
while(rs.next()) {
// set temp to equal the id rs.next() is currently on
String temp = rs.getString("id");
// get the row id - 1 since we start at 0
int temp1 = rs.getRow() - 1;
// if temp1 is equal to the index we selected
if(temp1 == initial) {
// make it equal to result
result = temp;
}
}
// close the connection
conn.close();
} catch (SQLException ex) {
ex.printStackTrace();
}
// return the row to delete
return result;
}
What's going on is in the comments. I finally figured out how to pass the value from a selected row and compare it to a row. Once I get the correct row to pass, I give it to the delete function to remove.
After a day in a half.............but I love it, so. Yeah.
I am currently working on a Java project (on NetBeans) and I am struggling with a problem.
In fact, I have a jTable which contains several elements, which element has a jCheckBox in the second column and I would like to make a query to add the selected element (selected by the jCheckBox of course) in a table.
I can get the data that I want to add, but my query works only once. I have already check my loop but I don't where the problem comes from.
I let you see the code :
try {
// Getting id of the selected value in the jComboBox
String idParcours = oParcoursDAO.findIdParcours(jComboBoxParcours.getSelectedItem().toString());
int id = Integer.parseInt(idParcours);
// for each value in the jTable
for(int i=0; i <jTable2.getRowCount(); i++){
boolean isChecked = (Boolean)jTable2.getValueAt(i, 1);
String nomPoi = (String)jTable2.getValueAt(i, 0);
// if the value is selected
if(isChecked){
String IDPoi = oParcoursDAO.findIdPoi(nomPoi);
int idpoi = Integer.parseInt(IDPoi);
System.out.println("idpoi "+idpoi); // It works I saw as idpoi as I have choose
System.out.println("id "+id) // It works too
oParcoursDAO.addPoi(idpoi,id); // it works only once
}
}
}catch (SQLException ex) {
Logger.getLogger(ModificationParcoursJInternalFrame.class.getName()).log(Level.SEVERE, null, ex);
}
Thank you in advance for your help.
This is my statement
public void addPoi(int idPoi,int idParcours) throws SQLException{
String query = "INSERT INTO TB_POI_PARCOURS (id_poi,id_parcours) VALUES (?,?) ";
PreparedStatement preparedStatement = conn.prepareStatement(query);
preparedStatement.setInt(1,idPoi);
preparedStatement.setInt(2,idParcours);
preparedStatement.executeUpdate();
preparedStatement.close();
}
Why are you running one query per line? You can execute all of them in a single SQL using batch queries. It will require you to change the code but it will make it more efficient:
public void addPoi(Map<integer,Integer> poiMap) throws SQLException{
String query = "INSERT INTO TB_POI_PARCOURS (id_poi,id_parcours) VALUES (?,?) ";
PreparedStatement preparedStatement = conn.prepareStatement(query);
for(Integer idPoi:poiMap.keySet()) {
preparedStatement.setInt(1,idPoi);
preparedStatement.setInt(2,poiMap.get(idPoi));
preparedStatement.addBatch();
}
preparedStatement.executeBatch();
preparedStatement.close();
}
Of course the original method has to be changed accordingly.
I want to check whether the newly entered data is already in the table
code:
txtNo = new JTextField();
{
try {
Class.forName("com.mysql.jdbc.Driver");
String srcurl1 = "jdbc:mysql://localhost:3306/DB_name";
Connection con = DriverManager.getConnection(srcurl1,"root","paswrd");
Statement stmt1 = con.createStatement();
ResultSet rs1 = stmt1.executeQuery("select No from bank where No='"+txtNo.getText()+"' ");
int ch =rs1.getInt("No");
int ch4= Integer.parseInt(txtNo.getText());
if(ch==ch4) // input 58 == 58
System.out.println("already exits");
}
catch(Exception e)
{
System.out.println("Exception:"+e);
}
}
Error :
Exception:java.sql.SQLException: Illegal operation on empty result set.
You need to check if the result set has elements or not:
while(rs1.next())
{
int ch = rs1.getInt("No");
// ...
}
You get this exception when the select statement returns an empty set. Add a try/catch block which acts upon the knowledge that the data is not already in the table in the catch block.
You need to check the ResultSet first to check to see that it contains rows:
if (rs1.next()) {
int ch =rs1.getInt("No");
...
}
The easiest way to check whether a particular record exists in the database might be just as follows:
Select 1 from bank where No = [your_supplied_value]
This query would return 1 if it finds a row in your database with the supplied data or return an empty resultset. So, all you need to check is whether ANY value is returned in the resultset or whether it is emtpy.
Here's a sample code to get you started:
txtNo = new JTextField();
{
try {
String compareText = txtNo.getText().trim();
if(compareText.length() > 0){
Class.forName("com.mysql.jdbc.Driver");
String srcurl1 = "jdbc:mysql://localhost:3306/DB_name";
Connection con = DriverManager.getConnection(srcurl1,"root","paswrd");
Statement stmt1 = con.createStatement();
ResultSet rs1 = stmt1.executeQuery("select 1 from bank where No='"+txtNo.getText()+"' ");
boolean isPresent = rs1.next();
if(isPresent){
System.out.println("Already exists!!");
}
}
}
catch(Exception e)
{
System.out.println("Exception:"+e);
}
}
I hope this is not your final code, because there're several problems with it:
You're not managing your resources properly. Once you're done querying your database, you should consider closing your resultset, statement and connection objects.
Note that I checked whether the text in the JTextField is empty or not. This is a good way of preventing a call to the database when you know that the text field had no value in it.
I would suggest using a PreparedStatement rather than a Statement for querying to your database.
A ResultSet is initially positioned before the first row. So you need to call next() to move it to the next row (and check that it returns true) before you call one of the getXXX() methods.
JTextField input = new JTextField();
ArrayList < Integer > list = new ArrayList < Integer > ();
int integerv = Integer.parseInt(input.getText());
try {
Class.forName("com.mysql.cj.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/DB_name", "root", "yourpassword");
Statement stm = con.createStatement();
ResultSet rs = stm.executeQuery("select column_name from table_name");
while (rs.next()) {
list.add(rs.getInt(1));
}
for (int a = 0; a < list.Size(); a++) {
if (a.get(a) == integerv) {
System.out.println("Match found");
break;
} else {
System.out.println("Match not found");
break;
}
}
} catch (Exception e) {
System.out.println("Error :" + e.getMessage());
}