0

これは JDBC プロジェクトです。WAMP サーバー上の mySql データベースからのデータが jtable に表示されます。ここで、ユーザーが入力した ID を Spinnerbutton に入力し、その ID を持つ行を削除します。SQL クエリを作成し、すべてが機能しましたが、クエリを実行しても myjtable のデータが更新されません。JNazad ボタン (戻るボタン) をクリックし、そのウィンドウに再度入ると、Jtable に更新されたデータが表示されます。NapraviTablicu メソッドで FireTableModel を正しく実装していないと思いますが、何が間違っていたのかわかりません。

public class GUIBDelete extends JFrame{

    private SpinnerModel SM;
    private JSpinner Spinner;
    private JLabel LUnos;
    private JButton BNazad, BIzvrsi;
    private String ID, SqlQuery;
    private Vector NaziviKolona = new Vector();
    private Vector Podaci = new Vector();
    private JTable Tablica=new JTable();
    private JScrollPane ScrollPane;
    private DefaultTableModel model;


    private JTable NapraviTablicu(){
        try {
            String SqlQuery = "SELECT * FROM `nfc_baza`";
            Podaci.clear();
            NaziviKolona.clear();
            Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
            Connection con = DriverManager.getConnection("jdbc:mysql://"
                    + "localhost:3306/nfc", "root", "");

            Statement Stat = con.createStatement();
            ResultSet Rez = Stat.executeQuery(SqlQuery);
            ResultSetMetaData md = Rez.getMetaData();
            int columns = md.getColumnCount();
            for (int i = 1; i <= columns; i++) {
                NaziviKolona.addElement(md.getColumnName(i));
            }
            while (Rez.next()) {
                Vector red = new Vector(columns);
                for (int i = 1; i <= columns; i++) {
                    red.addElement(Rez.getObject(i));
                }
                Podaci.addElement(red);
            }
            Rez.close();
            Stat.close();
            con.close();
        } catch (Exception e) {
            System.out.println(e);
        }
        model = new DefaultTableModel(Podaci, NaziviKolona);
        model.fireTableDataChanged();
        JTable table = new JTable(model);

        return table;

    }

    ActionListener a1 = new ActionListener() {
        public void actionPerformed(ActionEvent a) {
            dispose();
            new GUIIzbornik();
        }
    };

    ActionListener a2 = new ActionListener() {
        public void actionPerformed(ActionEvent a) {
            ID=null;
            SqlQuery = "DELETE FROM `nfc`.`nfc_baza` WHERE `nfc_baza`.`ID` = ";
            IzvrsiQuery();
            model.fireTableDataChanged();
        }

        private void IzvrsiQuery() {
            Object sp = Spinner.getValue();
            ID = sp.toString();
            SqlQuery=SqlQuery+ID;
            try {
                Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
                Connection con2 = DriverManager.getConnection(
                        "jdbc:mysql://" + "localhost:3306/nfc", "root", "");
                Statement Stat = con2.createStatement();
                int Rez = Stat.executeUpdate(SqlQuery);
                Stat.close();
                con2.close();
                JOptionPane.showMessageDialog(null, "Uspješno izvrseno!",
                        "Poruka!", JOptionPane.INFORMATION_MESSAGE);

            } catch (Exception e) {
                System.out.println(e);
            }


        }

    };


    GUIBDelete(){
        setLayout(new GridBagLayout());
        GridBagConstraints c = new GridBagConstraints();

        Tablica=NapraviTablicu();
        ScrollPane = new JScrollPane(Tablica);
        c.fill = GridBagConstraints.BOTH;
        c.insets = new Insets(2, 2, 2, 2);
        c.weightx = 0.1;
        c.weighty = 0.1;
        c.gridwidth = 4;
        c.gridheight = 2;
        c.gridx = 0;
        c.gridy = 0;
        add(ScrollPane, c);


        LUnos= new JLabel("<html><br>Unesite ID elementa</br> kojeg želite obrisati:<html>");
        c.gridx = 0;
        c.gridy = 2;
        c.gridwidth = 1;
        c.gridheight = 1;
        add(LUnos, c);

        SM = new SpinnerNumberModel(1, 1, 1000, 1);
        Spinner = new JSpinner(SM);
        c.gridx = 2;
        c.gridy = 2;
        c.gridwidth = 1;
        add(Spinner, c);

        BNazad = new JButton("Nazad");
        c.gridx = 0;
        c.gridy = 3;
        c.gridwidth = 1;
        BNazad.addActionListener(a1);
        add(BNazad, c);

        BIzvrsi = new JButton("Izvrši");
        c.gridx = 3;
        c.gridy = 3;
        BIzvrsi.addActionListener(a2);
        add(BIzvrsi, c);

        setSize(400, 500);
        setTitle("Brisanje podataka");
        setVisible(true);
        setLocationRelativeTo(null);

    }


    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                GUIBDelete i = new GUIBDelete();
            }
        });
    }
}

まず、あなたの答えに感謝します!

使用するPreparedStatementと、次の例外が発生します。

java.lang.ClassCastException: com.mysql.jdbc.StatementImpl cannot be 
  cast to java.sql.PreparedStatement 

..だから私はクラシックを使わなければならないStatement

JTableまた、毎回作成しないようにしました。NapraviTablicuメソッドでモデルを作成し、後でそのモデルをコンストラクターで table に追加するだけで使用しますTablicaが、現在、テーブルにはデータが表示されていません。コードにヒントを正しく実装したかどうかはわかりません...

public class GUIBDelete extends JFrame{

    private SpinnerModel SM;
    private JSpinner Spinner;
    private JLabel LUnos;
    private JButton BNazad, BIzvrsi;
    private String ID, SqlQuery;
    private Vector NaziviKolona = new Vector();
    private Vector Podaci = new Vector();
    private JTable Tablica=new JTable();
    private JScrollPane ScrollPane;
    private DefaultTableModel model;


    private void NapraviTablicu(){
        try {
            String SqlQuery = "SELECT * FROM `nfc_baza`";
            Podaci.clear();
            NaziviKolona.clear();
            Class.forName("com.mysql.jdbc.Driver");
            Connection con = DriverManager.getConnection("jdbc:mysql://"
                    + "localhost:3306/nfc", "root", "");

            Statement Stat = con.createStatement();
            ResultSet Rez = Stat.executeQuery(SqlQuery);
            ResultSetMetaData md = Rez.getMetaData();
            int columns = md.getColumnCount();
            for (int i = 1; i <= columns; i++) {
                NaziviKolona.addElement(md.getColumnName(i));
            }
            while (Rez.next()) {
                Vector red = new Vector(columns);
                for (int i = 1; i <= columns; i++) {
                    red.addElement(Rez.getObject(i));
                }
                Podaci.addElement(red);
            }
            Rez.close();
            Stat.close();
            con.close();

        } catch (Exception e) {
            System.out.println(e);
        }
        model = new DefaultTableModel(Podaci, NaziviKolona);
        //model.fireTableDataChanged();

    }

    ActionListener a1 = new ActionListener() {
        public void actionPerformed(ActionEvent a) {
            dispose();
            new GUIIzbornik();
        }
    };

    ActionListener a2 = new ActionListener() {
        public void actionPerformed(ActionEvent a) {
            ID=null;
            SqlQuery = "DELETE FROM `nfc`.`nfc_baza` WHERE `nfc_baza`.`ID` = ";
            IzvrsiQuery();
            //model.fireTableDataChanged();
        }

        private void IzvrsiQuery() {
            Object sp = Spinner.getValue();
            ID = sp.toString();
            SqlQuery=SqlQuery+ID;
            try {
                Class.forName("com.mysql.jdbc.Driver");
                Connection con2 = DriverManager.getConnection(
                        "jdbc:mysql://" + "localhost:3306/nfc", "root", "");
                PreparedStatement Stat = (PreparedStatement) con2.createStatement();
                int Rez = Stat.executeUpdate(SqlQuery);
                Stat.close();
                con2.close();
                JOptionPane.showMessageDialog(null, "Uspješno izvrseno!",
                        "Poruka!", JOptionPane.INFORMATION_MESSAGE);

            } catch (Exception e) {
                System.out.println(e);
            }


        }

    };


    GUIBDelete(){
        setLayout(new GridBagLayout());
        GridBagConstraints c = new GridBagConstraints();

        Tablica=new JTable(model);
        ScrollPane = new JScrollPane(Tablica);
        c.fill = GridBagConstraints.BOTH;
        c.insets = new Insets(2, 2, 2, 2);
        c.weightx = 0.1;
        c.weighty = 0.1;
        c.gridwidth = 4;
        c.gridheight = 2;
        c.gridx = 0;
        c.gridy = 0;
        add(ScrollPane, c);


        LUnos= new JLabel("<html><br>Unesite ID elementa</br> kojeg želite obrisati:<html>");
        c.gridx = 0;
        c.gridy = 2;
        c.gridwidth = 1;
        c.gridheight = 1;
        add(LUnos, c);

        SM = new SpinnerNumberModel(1, 1, 1000, 1);
        Spinner = new JSpinner(SM);
        c.gridx = 2;
        c.gridy = 2;
        c.gridwidth = 1;
        add(Spinner, c);

        BNazad = new JButton("Nazad");
        c.gridx = 0;
        c.gridy = 3;
        c.gridwidth = 1;
        BNazad.addActionListener(a1);
        add(BNazad, c);

        BIzvrsi = new JButton("Izvrši");
        c.gridx = 3;
        c.gridy = 3;
        BIzvrsi.addActionListener(a2);
        add(BIzvrsi, c);

        setSize(400, 500);
        setTitle("Brisanje podataka");
        setVisible(true);
        setLocationRelativeTo(null);

    }


    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                GUIBDelete i = new GUIBDelete();
            }
        });
    }
}
4

1 に答える 1

3

You need to use com.mysql.jdbc.Driver as your JDBC driver rather than the generic JDBC/ODBC one. Also there's no need to call fireTableDataChanged, your TableModel will call this under the hood.


Side Notes:

  • No need to create the JTable every time. DefaultTableModel is a mutable TableModel which can be updated.
  • PreparedStatement is considered safer than Statement
  • There's no need to extend JFrame if you're not adding new functionality. A direct instance is preferred.
  • For maintainability consider keeping your database/non UI code separate from your UI code.

Update:

To create a PreparedStatement, use Connection#prepareStatement rather than Connection#createStatement.

PreparedStatement Stat = con2.prepareStatement(SqlQuery);

Then when executing the query, it is necessary to use the execute statement with the empty argument list:

int rez = stat.executeUpdate();

Also better to place Statement & Connection & close statements in a finally block. Java uses an initial lowercase letter for variables names which would make SqlQuery sqlQuery.

于 2013-03-01T01:49:11.177 に答える