как следует из названия, я пытался удалить данные в таблице в моем SQLite с помощью кнопки. Мне удалось заставить его работать с другим классом, но, похоже, я не могу заставить его работать с этим конкретным классом, который я вам покажу.
кнопка называется btnDelete, а метод, который загружает базу данных и удаляет ее, называется delete_account.
Button btnDelete = new JButton("Delete Account");
btnDelete.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
delete_account();
}
});
public void delete_account(){
try { //start or try
//1)create a connection variable
Connection con;
//2)create an instance of the database class
Database db=new Database();
//3)pass the connection from DB to con
con=db.open_connection();
//4)create a statement variable to prepare the SQL
Statement statement=con.createStatement();
//5)create a query to insert the records
String query = "DELETE FROM tblUsers WHERE userID = "+ userid +"";
//6) execute the SQL code
if (statement.executeUpdate(query)==1) { //query was successful
JOptionPane.showMessageDialog(null, "Account successfully deleted!");
//clear the inputs
new MainInterface(user);
frmAccountSett.dispose();
}
}//end of try
catch (Exception e){//start of catch
//display the error
JOptionPane.showMessageDialog(null,e.getMessage());
}//end of catch
}//end of save_recipe()
Вот весь код класса на всякий случай:
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import javax.swing.JPasswordField;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.sql.*;
public class AccSettings {
private JFrame frmAccountSett;
private JTextField txtFullname;
private JTextField txtUsername;
private JPasswordField txtPassword;
private int userid;
private String user;
/**
* Create the application.
*/
public AccSettings(String username) {
user=username;
//userid = id;
initialize();
edit_account();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frmAccountSett = new JFrame();
frmAccountSett.setTitle("Account Settings");
frmAccountSett.setBounds(100, 100, 450, 300);
frmAccountSett.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frmAccountSett.getContentPane().setLayout(null);
JLabel lblUsername = new JLabel("Edit Username:");
lblUsername.setBounds(85, 62, 103, 14);
frmAccountSett.getContentPane().add(lblUsername);
txtUsername = new JTextField();
txtUsername.setBounds(229, 59, 137, 20);
frmAccountSett.getContentPane().add(txtUsername);
txtUsername.setColumns(10);
txtPassword = new JPasswordField();
txtPassword.setBounds(229, 90, 137, 20);
frmAccountSett.getContentPane().add(txtPassword);
JButton btnConfirm = new JButton("Confirm Changes");
btnConfirm.setBounds(146, 164, 137, 29);
frmAccountSett.getContentPane().add(btnConfirm);
JLabel lblPassword = new JLabel("Edit Password:");
lblPassword.setBounds(85, 93, 103, 14);
frmAccountSett.getContentPane().add(lblPassword);
frmAccountSett.setVisible(true);
JButton btnDelete = new JButton("Delete Account");
btnDelete.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
delete_account();
}
});
btnDelete.setBounds(299, 227, 125, 23);
frmAccountSett.getContentPane().add(btnDelete);
JButton btnBack = new JButton("<< Back");
btnBack.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
frmAccountSett.dispose();
}
});
btnBack.setBounds(10, 227, 103, 23);
frmAccountSett.getContentPane().add(btnBack);
JLabel lblFullname = new JLabel("Edit Fullname:");
lblFullname.setBounds(85, 31, 103, 14);
frmAccountSett.getContentPane().add(lblFullname);
txtFullname = new JTextField();
txtFullname.setColumns(10);
txtFullname.setBounds(229, 28, 137, 20);
frmAccountSett.getContentPane().add(txtFullname);
btnConfirm.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
update_account();
}
});
}
public void delete_account(){
try { //start or try
//1)create a connection variable
Connection con;
//2)create an instance of the database class
Database db=new Database();
//3)pass the connection from DB to con
con=db.open_connection();
//4)create a statement variable to prepare the SQL
Statement statement=con.createStatement();
//5)create a query to insert the records
String query = "DELETE FROM tblUsers WHERE userID = "+ userid +"";
//6) execute the SQL code
if (statement.executeUpdate(query)==1) { //query was successful
JOptionPane.showMessageDialog(null, "Account successfully deleted!");
//clear the inputs
new MainInterface(user);
frmAccountSett.dispose();
}
}//end of try
catch (Exception e){//start of catch
//display the error
JOptionPane.showMessageDialog(null,e.getMessage());
}//end of catch
}//end of save_recipe()
public void update_account(){
try { //start or try
//1)create a connection variable
Connection con;
//2)create an instance of the database class
Database db=new Database();
//3)pass the connection from DB to con
con=db.open_connection();
//4)create a statement variable to prepare the SQL
Statement statement=con.createStatement();
//5)create a query to insert the records
@SuppressWarnings("deprecation")
String query = "UPDATE tblUsers SET fullname='" + txtFullname.getText()+"',"
+ "username='" + txtUsername.getText()+"',"
+ "password='" + txtPassword.getText()+"'"
+ "WHERE userID = "+ userid +"";
//6) execute the SQL code
if (statement.executeUpdate(query)==1) { //query was successful
JOptionPane.showMessageDialog(null, "Reference successfully updated!");
//clear the inputs
new MainInterface(user);
frmAccountSett.dispose();
}
}//end of try
catch (Exception e){//start of catch
//display the error
JOptionPane.showMessageDialog(null,e.getMessage());
}//end of catch
}//end of save_recipe()
//load the results
public void edit_account()
{
try {
Connection con; //create a variable for con
Database db = new Database(); //create an instance of database class
con = db.open_connection(); //set con as connection form database class
Statement st;
st = con.createStatement();
//create a statement variable
//create the query that will search the table based on similar terms
String query = "SELECT * FROM tblUsers WHERE userID = " + userid+ "";
//get the resultset of the query (rows)
ResultSet rs = st.executeQuery(query);
if (rs.next())
{
do{
txtFullname.setText(rs.getString(2));
txtUsername.setText(rs.getString(3));
txtPassword.setText(rs.getString(4));
}
while(rs.next());
}
/*
else {
JOptionPane.showMessageDialog(null, "Edit failed");
}
*/
}
catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Я считаю, что проблема в основном связана с идентификатором пользователя, который указал zephyr. Я следил за кодом из другого класса (frmEditRef), но этот класс использует JScrollPane, который при вызове из другого класса (frmMainInterface) выглядит так:
public void mouseClicked(MouseEvent e) {
// TODO Auto-generated method stub
int x = table.getSelectedRow(); //get the current row
int ans = JOptionPane.showConfirmDialog(null, "Do you want to edit this record?");
if (ans == 0) {
//proceed to edit the transaction
//get the id
String id = String.valueOf(model.getValueAt(x, 0));
new EditRef(user,Integer.valueOf(id));
frmUserRef.dispose();
}
}
});
Класс, с которым я пытаюсь работать, не использует JScrollPane. Следовательно, кодировка будет другой. Вот как это выглядит из frmMainInterface:
btnAccountSett.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
String id = ;
new AccSettings(user,Integer.valueOf(id));
}
});
Как видите, я понятия не имею, что вставить после «String id =».
Я надеюсь, что это объяснение дойдет до вас, ребята. Я сам с трудом пытаюсь объяснить то, чего даже не понимаю полностью.
мой плохой ... Я имел в виду все смыслы этого слова. В частности, когда я нажимаю кнопку (btnDelete) в программе, ничего не происходит. Он не обновляется, не выдает никаких ошибок и т. д. Я щелкнул по нему, и это все.
Какую отладку вы сделали? deleteAccount() когда-нибудь вызывается? Правильно ли userId добавлен в оператор SQL?
@Zephyr Я не занимался отладкой, я также очень не знаком с этим словом (я знаю только основы программирования). Лектор, который меня учил, не очень хорошо учил, но не будем вдаваться в подробности. «deleteAccount ()» вызывается, когда я нажимаю кнопку. и userID ... позвольте мне отредактировать мой исходный пост, и я объясню его через минуту.
Начните с распечатки некоторых значений во время работы вашей программы. Например, попробуйте распечатать userId непосредственно перед оператором SQL, чтобы убедиться, что это именно то, что вы ожидаете.




Просто сказать, что что-то «не работает», а затем предоставить весь свой код, для нас совершенно бесполезно. Пожалуйста, прочтите статью Как спросить и соответственно редактировать свой вопрос. Вам необходимо указать точную ошибку или проблему, с которой вы столкнулись.