我如何使用java swing将日期从jdatepicker插入到mysql数据库中

时间:2018-02-21 21:35:19

标签: java mysql

我已将java.util.date转换为String而不是java.sql并将所选日期作为String插入到具有date数据类型的Mysql列中。成功插入所选日期我无法将其作为java.sql.Date插入。有想法的任何人请与我们分享....

这是完整代码

import java.awt.EventQueue;
import java.awt.HeadlessException;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.text.DateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Properties;
import javax.swing.JButton;
import javax.swing.JFormattedTextField.AbstractFormatter;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
//import jdk.nashorn.internal.ir.Statement;
//import static sun.misc.ClassFileTransformer.add;
   import org.jdatepicker.impl.JDatePanelImpl;
    import org.jdatepicker.impl.JDatePickerImpl;
    import org.jdatepicker.impl.UtilDateModel;
    import java.sql.*;
    import java.util.Date.*;
    import java.util.Date;
    import javax.swing.*;

public class Testd {

    Connection con = null;
    Statement st;
    ResultSet rs;
    PreparedStatement pst = null;
    JButton btn;
    //Date datee;

    public static void main(String[] args) {
        new Testd();
    }

    public Testd() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                    ex.printStackTrace();
                }

                JFrame frame = new JFrame("Testing");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.add(new TestPane());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
                frame.setLayout(null);
            }
        });
    }

    public class TestPane extends JPanel {

        public TestPane() {
            btn = new JButton("Add");
            btn.setBounds(280, 350, 200, 30);

            UtilDateModel model = new UtilDateModel();
            Properties p = new Properties();
            p.put("text.today", "Today");
            p.put("text.month", "Month");
            p.put("text.year", "Year");
            JDatePanelImpl datePanel = new JDatePanelImpl(model, p);
            JDatePickerImpl datePicker = new JDatePickerImpl(datePanel, new DateLabelFormatter());
            datePicker.setBounds(220, 350, 120, 50);

            //datee = (Date) datePicker.getModel().getValue();
            //  datee=selectedDate+"";
            add(datePicker);
            add(btn);

            btn.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent evt) {
                    try {


                        Date datee = (Date) datePicker.getModel().getValue();
                        DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
                        String reportDate = df.format(datee);
                        JOptionPane.showMessageDialog(null,reportDate);

                        if (datee != null) {
                           // java.sql.Date sqlDate = new java.sql.Date(reportDate.getText());
                            String sql = "INSERT INTO Invoice"
                                    + "(DueDate)"
                                    + "VALUES (?)";

                           con = DriverManager.getConnection("jdbc:mysql://localhost/Sales"+"?useSSL=false","root","8000");
                           pst = con.prepareStatement(sql);
                           pst.setString(1,reportDate);
                           pst.executeUpdate();

                        } else {
                            JOptionPane.showMessageDialog(TestPane.this, "You need to select a date");
                        }
                    } catch (SQLException | HeadlessException ex) {
                        JOptionPane.showMessageDialog(TestPane.this, "ERROR UNABLE TO INSERT ");
                        JOptionPane.showMessageDialog(TestPane.this, ex);

                    }
                }
            });
        }

    }

    public class DateLabelFormatter extends AbstractFormatter {

        private String datePattern = "yyyy-MM-dd";
        private SimpleDateFormat dateFormatter = new SimpleDateFormat(datePattern);

        @Override
        public Object stringToValue(String text) throws ParseException {
            return dateFormatter.parseObject(text);
        }

        @Override
        public String valueToString(Object value) throws ParseException {
            if (value != null) {
                Calendar cal = (Calendar) value;
                return dateFormatter.format(cal.getTime());
            }

            return "";
        }

    }
}

1 个答案:

答案 0 :(得分:0)

datee = (Date) datePicker.getModel().getValue();构造函数中的调用TestPane没有任何意义,因为用户尚未选择该值,日期选择器甚至未添加到面板中,面板没有添加到框架中,框架也没有显示在屏幕上。

您需要在ActionListener actionPerformed方法中执行此操作,但仍要检查它是否null

以下示例使用H2, in memory database。此示例还显示要插入的内容和插入的内容。请注意 - 这是H2如何工作的怪癖,因为我只是列出invoice表中的所有值,但它是屏幕上显示的最后一个值。最好改为使用System.out语句;)

Inserting dates

import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.HeadlessException;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Properties;
import javax.swing.JButton;
import javax.swing.JFormattedTextField.AbstractFormatter;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import org.jdatepicker.impl.JDatePanelImpl;
import org.jdatepicker.impl.JDatePickerImpl;
import org.jdatepicker.impl.UtilDateModel;

public class Testd {

    JButton btn;
    //Date datee;

    private JLabel input;
    private JLabel output;

    public static void main(String[] args) {
        new Testd();
    }

    public Testd() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                    ex.printStackTrace();
                }

                JFrame frame = new JFrame("Testing");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                try {
                    frame.add(new TestPane());
                    frame.pack();
                    frame.setLocationRelativeTo(null);
                    frame.setVisible(true);
                    frame.setLayout(null);
                } catch (SQLException ex) {
                    ex.printStackTrace();
                }
            }
        });
    }

    public class TestPane extends JPanel {

        private Connection con;

        public TestPane() throws SQLException {
            make();

            setLayout(new GridBagLayout());
            GridBagConstraints gbc = new GridBagConstraints();
            gbc.gridx = 0;
            gbc.gridy = 0;

            btn = new JButton("Add");

            UtilDateModel model = new UtilDateModel();
            Properties p = new Properties();
            p.put("text.today", "Today");
            p.put("text.month", "Month");
            p.put("text.year", "Year");
            JDatePanelImpl datePanel = new JDatePanelImpl(model, p);
            JDatePickerImpl datePicker = new JDatePickerImpl(datePanel, new DateLabelFormatter());

            JPanel top = new JPanel();

            top.add(datePicker);
            top.add(btn);

            add(top, gbc);

            input = new JLabel("---");
            output = new JLabel("---");

            JPanel bottom = new JPanel();
            bottom.add(input);
            bottom.add(output);

            gbc.gridx = 0;
            gbc.gridy = 1;
            add(bottom, gbc);

            btn.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent evt) {
                    try {
                        // String text = datee;
                        // DateFormat formatter = new SimpleDateFormat("dd-MM-yyyy");
                        // Date myDate = formatter.parse(text);
                        java.util.Date datee = (java.util.Date) datePicker.getModel().getValue();
                        if (datee != null) {
                            java.sql.Date sqlDate = new java.sql.Date(datee.getTime());

                            String sql = "INSERT INTO Invoice"
                                            + "(Issuedate)"
                                            + "VALUES (?)";

                            input.setText(sqlDate.toString());

                            try (PreparedStatement stmt = con.prepareStatement(sql)) {
                                stmt.setDate(1, sqlDate);
                                int rowCount = stmt.executeUpdate();
                                System.out.println(rowCount);
                                con.commit();
                            }

                            select();

                        } else {
                            JOptionPane.showMessageDialog(TestPane.this, "You need to select a date");
                        }
                    } catch (SQLException | HeadlessException ex) {
                        ex.printStackTrace();
                        JOptionPane.showMessageDialog(TestPane.this, ex);

                    }
                }
            });
        }

        protected void select() throws SQLException {
            try (PreparedStatement stmt = con.prepareStatement("select * from Invoice")) {
                try (ResultSet rs = stmt.executeQuery()) {
                    while (rs.next()) {
                        java.sql.Date date = rs.getDate(1);
                        output.setText(date.toString());
                    }
                }
            }
        }

        protected void make() throws SQLException {
            con = DriverManager.getConnection("jdbc:h2:mem:");
            try (Statement stmt = con.createStatement()) {
                boolean result = stmt.execute("create table Invoice( Issuedate date not null )");
                System.out.println(result);
                con.commit();
                select();
            }
        }
    }

    public class DateLabelFormatter extends AbstractFormatter {

        private String datePattern = "yyyy-MM-dd";
        private SimpleDateFormat dateFormatter = new SimpleDateFormat(datePattern);

        @Override
        public Object stringToValue(String text) throws ParseException {
            return dateFormatter.parseObject(text);
        }

        @Override
        public String valueToString(Object value) throws ParseException {
            if (value != null) {
                Calendar cal = (Calendar) value;
                return dateFormatter.format(cal.getTime());
            }

            return "";
        }

    }
}

如果您仍然遇到问题,我强烈建议您创建一个简单的项目,删除UI并完全专注于使用数据库,这样您就可以更好地了解如何使用JDBC和数据库