So i try to create a JTable which connect to SQL server database by JBDC, and have a function like insert, delete, and edit the data. It work well with insert but update, delete. Can you guys show me why i got ArrayIndexOutOfBoundsException: -1 and how to fix it. Here 's my code. Book here is a class extends JFRAME
public Book() {
initComponents();
model.addColumn("ID");
model.addColumn("Name");
model.addColumn("Type");
jTable1.setModel(model);
displayTable();
jTable1.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
#Override
public void valueChanged(ListSelectionEvent e) {
int row = jTable1.getSelectedRow();
txtName.setText(jTable1.getValueAt(row, 1).toString());
txtType.setText(jTable1.getValueAt(row, 2).toString());
}
});
}
public void displayTable() {
try {
model.setRowCount(0);
ConnectToSQL sql = new ConnectToSQL();
connection = sql.getConnection();
st = connection.createStatement();
ResultSet result = st.executeQuery("SELECT * FROM BOOK");
while (result.next()) {
model.addRow(new Object[]{result.getInt("id"), result.getString("name"), result.getString("type")});
}
} catch (SQLException ex) {
Logger.getLogger(Book.class.getName()).log(Level.SEVERE, null, ex);
}
}
private void btnUpdateActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
int row = jTable1.getSelectedRow();
String id = jTable1.getValueAt(row, 0).toString();
try {
// TODO add your handling code here:
st.executeUpdate("Update Book set name ='" + txtName.getText() + "',type='" + txtType.getText() + "' where id =" + id);
displayTable();
} catch (SQLException ex) {
Logger.getLogger(Book.class.getName()).log(Level.SEVERE, null, ex);
}
}
private void btnDeleteActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
int row = jTable1.getSelectedRow();
String id = jTable1.getValueAt(row, 0).toString();
try {
// TODO add your handling code here:
st.executeUpdate("Delete from book where id =" + id);
displayTable();
} catch (SQLException ex) {
Logger.getLogger(Book.class.getName()).log(Level.SEVERE, null, ex);
}
}
You get this error, because you don't select any row, so to avoid this problem you have to use :
if(jTable1.getSelectedRow() != -1){
int row = jTable1.getSelectedRow();
String id = jTable1.getValueAt(row, 0).toString();
//rest of your code here
}else{
//show an error for example, no row is selected
}
Note
Instead of :
st.executeUpdate("Update Book set name ='" + txtName.getText() + "',type='" + txtType.getText() + "' where id =" + id);
You have to use PreparedStatement to avoid any syntax error or SQL Injection
For example :
String query = "Update Book set name = ?, type=? where id =?";
try (PreparedStatement update = connection.prepareStatement(query)) {
update.setString(1, txtName.getText());
update.setString(2, txtType.getText());
update.setInt(3, id);
update.executeUpdate();
}
Another thing, your id is an int so you can't set a String to your query like you do you have to set an int :
String id = jTable1.getValueAt(row, 0).toString();
Instead you have to use :
int id = Integer.parseInt(jTable1.getValueAt(row, 0).toString());
Related
i tried to load the JcomboBox with some query by JOIN to other table and the item in the JcomboBox is id from table1, name from table2, loan date from table1. When I select the item from JcomboBox I want to fill the JTextField with loan amount from table1.
This is my loadCombo
public void loadComboGadai() {
try {
comboDataGadai.removeAllItems();
comboDataGadai.addItem("-- Pilih --");
sql = "SELECT * FROM gadai INNER JOIN nasabah ON gadai.ktp_gadai = nasabah.ktp";
res = stat.executeQuery(sql);
while(res.next()) {
String no_Gadai = res.getString("no_gadai");
String nama_Nasabah = res.getString("nama_nasabah");
String jatuh_tempo = res.getString("jatuh_tempo");
comboDataGadai.addItem(no_Gadai+" : "+nama_Nasabah+" : "+jatuh_tempo);
}
} catch (Exception e) {
}
}
And this is get data from the combo
public void getGadai() {
try {
if (comboDataGadai.getSelectedIndex() > 0) {
comboDataGadai.setSelectedIndex(-1);
sql = "SELECT * FROM gadai INNER JOIN nasabah ON gadai.ktp_gadai = nasabah.ktp";
res = stat.executeQuery(sql);
if (res.next()) {
String jumlah_Tebusan = res.getString("jumlah_tebusan");
txtJumlahTebusan.setText(jumlah_Tebusan);
}
}
} catch (Exception e) {
}
}
i am trying to making an update button in my GUI form that can be edit a record in my DB but i missing something that i hope someone to help me
this the code of update method:
public int updateUser(Login user) //int
{
DatabaseConnection dbconn = new DatabaseConnection();
Connection conn = dbconn.getConn();
int rows = 0;
try
{
String sql = "UPDATE LOGIN set USER_NAME = ? , PASSWORD = ? , PRIVILEGE_ID = ?";
PreparedStatement pStm = conn.prepareStatement(sql);
//fill SQL parameters from user: //
pStm.setString(1, user.getUserName());
pStm.setString(2, user.getPassword());
pStm.setInt(3, user.getPrivilegeId());
rows =
pStm.executeUpdate();
}
catch (SQLException ex) {
System.out.println("SQLException: " + ex.getMessage());
}
finally
{
try {
conn.close();
} catch (SQLException ex) {
System.out.println("SQLException: " + ex.getMessage());;
}
}
return rows;
}
code in java swing for update button:
private void updateUserLayerActionPerformed(java.awt.event.ActionEvent evt) {
// 1-get data from user and check it: //
String _name = nameLayer.getText().trim();
String _paswrd = passLayer.getText().trim();
String _prvName = privLayer.getSelectedItem().toString();
//get Privilege_Id from DB:
PrivilegeHandeler prvHndler = new PrivilegeHandeler();
int prvId = prvHndler.getPrivilegeByName(_prvName);
if(_name.length() >0 && _paswrd.length() >0 && prvId> 0)
{
Login user = new Login();
user.setUserName(_name);
user.setPassword(_paswrd);
user.setPrivilegeId(prvId);
//update User: //
loginHandeler loghndlr = new loginHandeler();
int rows =
loghndlr.updateUser(user);
if (rows >0)
{
usrFormErorr.setText("user has been added successfully :)");
nameLayer.setText("");
passLayer.setText("");
privLayer.setSelectedIndex(0);
}
else
{
usrFormErorr.setText("updated failed, try again");
}
}
else
{
usrFormErorr.setText("please, fill the required fields first");
}
}
My problem is this:
1-i am trying to enter an info to edit then update but always get an error updated failed, try again that i made it to get a message when there is a problem
Kindly help. A working code would be very highly appreciated. Thanks in advance.
i have problem with my project, and it still new for me with MYSQL, i want to get data from database and do some calculation and update the value on it,
its like making withdraw function like ATM machine. This my table look like.
enter image description here . You can see constructor parameter that carry value (String value and String ID). For Value="100"; and ID="5221311" you can see it on my table picture.
public ConformWithdraw() {
initComponents();
try {
Class.forName("com.jdbc.mysql.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:/atm", "root", "");
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
public ConformWithdraw(String value,String ID) {
initComponents();
this.value=value;
this.ID=ID;
}
------------------------------------------------------------
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
try {
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/atm?zeroDateTimeBehavior=convertToNull", "root", "");
String validate = "SELECT * FROM customer_details WHERE accountID LIKE '" + ID
+ "'";
PreparedStatement smtm = con.prepareStatement(validate);
ResultSet resultSet = smtm.executeQuery();
User user = null;
if (resultSet.next()) {
user = new User();
user.setBalance(resultSet.getString("accountBalance"));
double balance=Double.parseDouble(user.getBalance());
double val=Double.parseDouble(value);
total =(balance - val);
}
smtm.close();
resultSet.close();
program();
} catch (SQLException | HeadlessException | ClassCastException ex) {
JOptionPane.showMessageDialog(null, ex);
}
}
-------------------------------------------------------------
public void program(){
String sqlUpdate = "UPDATE customer_details "
+ "SET accountBalance = '"+String.valueOf(total)+"'"
+ "WHERE accountID = '"+ID+"'";
try{
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/atm?zeroDateTimeBehavior=convertToNull", "root", "");
PreparedStatement pstmt = con.prepareStatement(sqlUpdate);
id=Integer.parseInt(ID);
pstmt.setString(1, String.valueOf(total));
pstmt.setInt(2, id);
int rowAffected = pstmt.executeUpdate();
pstmt.close();
new ShowWithdraw().setVisible(true);
dispose();
}catch(SQLException | HeadlessException | ClassCastException ex){
JOptionPane.showMessageDialog(null, ex);
JOptionPane.showMessageDialog(null, "slh sini");
}
}
You are already setting the parameters on the query, so It tries to set the parameters and find no parameters to find. Try this:
String sqlUpdate = "UPDATE customer_details "
+ "SET accountBalance = ?"
+ "WHERE accountID = ?";
I have a JTable which acts as an order pane. When I complete an order and click a JButton called "New Order" it clears the JTable and it also clears the order specifics such as price and change etc. What I am trying to do when I click the "New Order" JButton is to deduct the stock that was sold in the last order before it was cleared.
I have a table in my SQL database with products which have columns called:
ProductID (PK), ProductName, ProductDescrp, Type, SupplierName, Quantity, Price
My goal in all of this is to reduce the Quantity in stock in the database on any product that has been sold in an order. This is my code so far.
jbtNewOrder.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
if(e.getSource().equals(jbtNewOrder))
{
total = 0.0;
totalTF.setText("");
tenderedTF.setText("");
changeTF.setText("");
model.setRowCount(0);
try
{
int prodID = 0;
String sql = ("UPDATE product " + "SET Quantity = Quantity -1" + (getDBQuantity(prodID)-1) + " WHERE ProductID = " + prodID);
databaseUpdate(sql);
}
catch(Exception e1)
{
e1.printStackTrace();
}
return status;
}
// return quantity of a product in DB
public int getDBQuantity(int prodID)
{
int quantity=0;
try
{
Class.forName("com.mysql.jdbc.Driver");
Connection conn = (Connection) DriverManager.getConnection(DB_URL, USER_NAME, PASSWORD);
statement = (Statement) conn.createStatement();
resultSet = statement.executeQuery("select Quantity from team_project.product WHERE ProductID = " + prodID);
while (resultSet.next())
{
quantity = (resultSet.getInt("Quantity"));
}
conn.close();
}catch(Exception e)
{
e.printStackTrace();
}
return quantity;
}}
private int databaseUpdate(String sqlUpdate)
{
int status = 0;
try{
Class.forName("com.mysql.jdbc.Driver");
Connection conn = (Connection) DriverManager.getConnection(DB_URL, USER_NAME, PASSWORD);
statement = conn.createStatement();
status = statement.executeUpdate(sqlUpdate);
conn.close();
}
catch (Exception e) {
e.printStackTrace();
}
return status;
}
I have these two methods where I was told that "the fact you allow the column name to be specified is (an SQL) injection risk". What does even mean? To be specified by whom? And how can I fix it?
public void tableChanged(TableModelEvent e) {
int row = e.getFirstRow();
int col = e.getColumn();
model = (MyTableModel) e.getSource();
String stulpPav = model.getColumnName(col);
Object data = model.getValueAt(row, col);
Object studId = model.getValueAt(row, 0);
System.out.println("tableChanded works");
try {
new ImportData(stulpPav, data, studId);
bottomLabel.setText(textForLabel());
} catch (ClassNotFoundException e1) {
e1.printStackTrace();
} catch (SQLException e1) {
e1.printStackTrace();
}
}
public class ImportData {
public ImportData(String a, Object b, Object c)
throws ClassNotFoundException, SQLException {
PreparedStatement prepStmt = null;
try {
connection = TableWithBottomLine.getConnection();
String stulpPav = a;
String duom = b.toString();
String studId = c.toString();
System.out.println(duom);
String updateString = "update finance.fin " + "set ? = ? " + "where ID = ? "+ ";";
prepStmt = connection.prepareStatement(updateString);
prepStmt.setString(1, stulpPav);
prepStmt.setString(2, duom);
prepStmt.setString(3, studId);
} catch (SQLException e) {
e.printStackTrace();
} finally {
if (prepStmt != null)
prepStmt.close();
System.out.println("Data was imported to database");
}
}
}
What does even mean? :)
It means, that if the String was changed, you could put in SQL code to do something different, like updating a password, or garnting access to the systems.
To be specified by whom?
Any code which can access the column name, this is only a problem if the user has access to this field.
And how can I fix it?
Check that there really is no way for the user to specify this column name, and ignore the message