【问题标题】:delete data from database using JDBC使用 JDBC 从数据库中删除数据
【发布时间】:2015-09-17 10:46:45
【问题描述】:

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

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

如何获取表名?

图形界面:

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);
    }

}

【问题讨论】:

  • 你的问题有点混乱。当您在代码中查询它们时,您 拥有 表名。你想删除所有四个表吗?还是您希望用户选择要删除的特定表?
  • @CraigOtis 特定表
  • 您可以使用 var 来存储 JTable 中显示的数据类型。在您的删除语句中,您可以测试这个 var 以了解您必须查询的表。
  • 删除按钮旁边的下拉菜单怎么样?
  • 我从代码中了解到:一个 jtable,许多按钮“显示球员”,“显示比赛”(...),它们提供相同的 jtable。和一个删除按钮。问题是 rokky 从不存储 jtable 中显示的数据类型。

标签: java mysql swing jdbc


【解决方案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 变量。例如:

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();
                }

            }
        });

【讨论】:

  • 我已经这样做了,但它给出了异常:“你的 SQL 语法有错误”:(
  • 如果你想删除所有记录,那么就这样写:" delete from table_name "
【解决方案2】:

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

Statement stmt = con.createStatement();
stmt.execute("delete from "+tableName);

【讨论】:

  • 问题是:“我怎样才能得到表名?”
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-11-29
  • 2013-08-16
  • 1970-01-01
  • 2021-04-09
  • 1970-01-01
  • 2021-12-08
相关资源
最近更新 更多