Mysql Java Update Query

时间:2014-08-28 09:47:59

标签: java mysql sql-update

我有一个监听器,它监听一个按钮并从输入中获取3个文本字段以执行更新查询。我想执行更新,但在查询中传递我的本地变量(名称,城市,工资)。 我能做什么?

public void actionPerformed(ActionEvent arg0) {
        final String name;
        final String city;
        final String salary; 

        name = (textFieldName.getText());   
        city = (textFieldCity.getText());   
        salary = (textFieldSalary.getText());   

        System.out.println(salary);
        try {
                Statement s = connection.createStatement();
                s.executeUpdate("INSERT INTO users (name,city,salary) VALUES (name, city,salary)");

1 个答案:

答案 0 :(得分:2)

我会选择PreparedStatement

PreparedStatement s = connection.prepareStatement("INSERT INTO users (name,city,salary) VALUES (?, ?, ?)");
s.setString(1, name);
s.setString(2, city);
s.setString(3, salary);
boolean res = s.execute();

这种方法稍好一些,引用会自动管理,并会阻止简单的SQL注入。