使用JDBC从数据库中删除数据

时间:2015-09-17 10:46:46

标签: java mysql swing jdbc

我的数据库包含4个表格(玩家,成就,匹配,锦标赛)。使用JTable显示数据。单击“删除”按钮时,我想从表中删除数据。问题是我不知道用户想要修改的表的名称,所以我无法编写正确的SQL语句

PreparedStatement pstm = con.prepareStatement("delete * from ?");

如何获取表名?

GUI:

public class FbGui {
    private JFrame frame;
    private JTable table;

    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    FbGui window = new FbGui();
                    window.frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * Create the application.
     */
    public FbGui() {
        initialize();
    }

    /**
     * Initialize the contents of the frame.
     */
    Connection con = null;

    private void initialize() {
        con = FbConnect.dbConnector();

        frame = new JFrame();
        frame.setBounds(100, 100, 642, 422);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().setLayout(null);

        JScrollPane scrollPane = new JScrollPane();
        scrollPane.setBounds(189, 39, 427, 120);
        frame.getContentPane().add(scrollPane);

        table = new JTable();
        scrollPane.setViewportView(table);

        JButton btnShowPlayers = new JButton("Show players");
        btnShowPlayers.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {

                try {
                    PreparedStatement pstm = con.prepareStatement("select * from fbdb.players");
                    ResultSet rs=pstm.executeQuery();
                    table.setModel(buildTableModel(rs));

                } catch (SQLException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }
            }
        });
        btnShowPlayers.setBounds(31, 36, 148, 23);
        frame.getContentPane().add(btnShowPlayers);

        JButton btnShowAchievements = new JButton("Show achievements");
        btnShowAchievements.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent arg0) {
                try {
                    PreparedStatement pstm = con.prepareStatement("select * from fbdb.achievements");
                    ResultSet rs=pstm.executeQuery();
                    table.setModel(buildTableModel(rs));

                } catch (SQLException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }

            }
        });
        btnShowAchievements.setBounds(31, 70, 148, 23);
        frame.getContentPane().add(btnShowAchievements);


        JButton btnShowTournaments = new JButton("Show tournaments");
        btnShowTournaments.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                try {
                    PreparedStatement pstm = con.prepareStatement("select * from fbdb.tournaments");
                    ResultSet rs=pstm.executeQuery();
                    table.setModel(buildTableModel(rs));

                } catch (SQLException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }
            }
        });
        btnShowTournaments.setBounds(31, 104, 148, 23);
        frame.getContentPane().add(btnShowTournaments);

        JButton btnShowMatches = new JButton("Show matches");
        btnShowMatches.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                try {
                    PreparedStatement pstm = con.prepareStatement("select * from fbdb.matches");
                    ResultSet rs=pstm.executeQuery();
                    table.setModel(buildTableModel(rs));

                } catch (SQLException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }
            }
        });
        btnShowMatches.setBounds(31, 136, 148, 23);
        frame.getContentPane().add(btnShowMatches);



        JButton btnDelete = new JButton("Delete");
        btnDelete.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                try {
                    PreparedStatement pstm = con.prepareStatement("delete * from ?");
                    pstm.execute();
                } catch (SQLException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }

            }
        });
        btnDelete.setBounds(208, 181, 89, 23);
        frame.getContentPane().add(btnDelete);
    }

    public static DefaultTableModel buildTableModel(ResultSet rs)
            throws SQLException {

        ResultSetMetaData metaData = rs.getMetaData();

        // names of columns
        Vector<String> columnNames = new Vector<String>();
        int columnCount = metaData.getColumnCount();
        for (int column = 1; column <= columnCount; column++) {
            columnNames.add(metaData.getColumnName(column));
        }

        // data of the table
        Vector<Vector<Object>> data = new Vector<Vector<Object>>();
        while (rs.next()) {
            Vector<Object> vector = new Vector<Object>();
            for (int columnIndex = 1; columnIndex <= columnCount; columnIndex++) {
                vector.add(rs.getObject(columnIndex));
            }
            data.add(vector);
        }

        return new DefaultTableModel(data, columnNames);
    }

}

2 个答案:

答案 0 :(得分:1)

这样做: 把一个临时变量作为

String whichTable="";

当您在此变量中单击表的按钮存储名称时,例如

btnShowPlayers.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {

                try {
                    PreparedStatement pstm = con.prepareStatement("select * from fbdb.players");
                    ResultSet rs=pstm.executeQuery();
                    table.setModel(buildTableModel(rs));        
                    whichTable="fbdb.player;";//do this.


                } catch (SQLException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }
            }
        });

对其他按钮操作执行相同操作 并在您的删除按钮操作中使用此whichTable变量。 e.g:

JButton btnDelete = new JButton("Delete");
        btnDelete.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                try {
                    PreparedStatement pstm = con.prepareStatement("delete * from "+whichTable);//put where condition also if required .
                    pstm.execute();
                } catch (SQLException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }

            }
        });

答案 1 :(得分:0)

您不能在PreparedStatement中使用问号作为占位符。您需要使用正常的声明,例如:

public class SingletonExampleTest{
  public static void main(String... args){
    java.util.Date date = Calendar.getInstance().getTime();
    SingletonExample singleton = SingletonExample.getInstance();
    String mask = "DD-MM-YYYY";
    DateFormat df = singleton.createDateFormat(mask);
    System.out.println(df.format(date));
  }
}