无法在Javafx控制器中调用方法

时间:2017-03-19 14:20:08

标签: java mysql jdbc javafx-8

我正在使用JavaFX应用程序,它允许我从注册表单中将新用户插入到mysql数据库中。我已经准备好了添加用户方法但是如何在控制器中调用它?这是我的方法:

    @Override
    public void adduser(User usr){
        String req="INSERT INTO `fos_user` (`id`, `username`, `username_canonical`, `email`, `email_canonical`, `enabled`, `password`, `roles`, `nom`) "
                + "VALUES (?,?,?,?,?,?,?,?,?)";
         try {
            Statement stm = con.createStatement();
            stm.executeUpdate(req);
            System.out.println("ajout ok");
        } catch (SQLException ex) {
        } 
    }

1 个答案:

答案 0 :(得分:1)

你正在以错误的方式使用PreparedStatement。

您没有为查询设置值,因此您必须设置一个值来代替每个?,例如第一个?意味着您应该设置ID,第二个{}用户名,......等等。

@Override
public void adduser(User usr){
     String req="INSERT INTO `fos_user` (`id`, `username`, `username_canonical`, `email`, `email_canonical`, `enabled`, `password`, `roles`, `nom`) "
                + "VALUES (?,?,?,?,?,?,?,?,?)";

     try {
        PreparedStatement stm = connection.prepareStatement(req);

        stm.setInt(1, user.getId());
        stm.setString(2, user.getUsername());
        stm.setString(3, user.getUsername_canonical());
        ...

        stm.executeUpdate();//execute your statement
        System.out.println("ajout ok");
    } catch (SQLException ex) {
    } 

注意

对于良好的做法,id应为自动增量,因此在插入时您无需插入它,请将其设置为正确。