插入数据的用户已输入mysql(java)

时间:2015-09-28 08:22:25

标签: java mysql textfield sql-insert

这是textField的代码,用户将在程序启动后插入数据。它不会更新mysql表。为什么它不起作用?

textField = new JTextField();
    textField.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {

            try {Class.forName("com.mysql.jdbc.Driver");
                Connection conn = DriverManager.getConnection("jdbc:mysql://localhost/csprogram","root","");
                price=scan.next();
                String query = "INSERT * INTO `graphics` (price (KM)) VALUES (?);";
                PreparedStatement preparedStmt = conn.prepareStatement(query);
                 preparedStmt.setString (1, price);
                 preparedStmt.executeUpdate();
            }
                catch (Exception d) {
                System.out.println("Error found "+ d);
            }

        }
    });

2 个答案:

答案 0 :(得分:0)

你正在使用actionPerformed()方法做一切,这是方法的本地方法。如果你想更新mysql表,你可以打开相同的东西或相应地更改你的程序。

答案 1 :(得分:0)

试试这个,

textField = new JTextField();
textField.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {

        try {Class.forName("com.mysql.jdbc.Driver");
            Connection conn = DriverManager.getConnection("jdbc:mysql://localhost/csprogram","root","");
            price=scan.next();
// Insert query shouldn't have *
            String query = "INSERT INTO `graphics` (price (KM)) VALUES (?);";
            PreparedStatement preparedStmt = conn.prepareStatement(query);
             preparedStmt.setString (1, price);
             preparedStmt.executeUpdate();
        }
            catch (Exception d) {
            System.out.println("Error found "+ d);
        }

    }
});