开发者社区> 问答> 正文

将nvarchar值“…”转换为数据类型int时转换失败

我正在尝试为JavaFx中的表创建更新语句,并且收到以下错误消息:

将nvarchar值“ Ana”转换为数据类型int时,转换失败。

我在SQL Server中创建了表。在我的数据库中,年龄仅来自int类型,其他所有内容均为字符串。

这是我的代码:

public void handleUpdateAction(ActionEvent event) {
    String sql = "update users set name =?, age = ?, department=?, job=?,  contact = ? where userNo =?" ;
    try {

        String userNo = txt_userNo.getText();
        String name = txt_name.getText();
        double age = Double.valueOf(txt_age.getText());
        String department = txt_department.getText();
        String job = txt_job.getText();
        String contact = txt_contact.getText();
        p_stmt = con.prepareStatement(sql);



        p_stmt.setString(1, userNo);
        p_stmt.setString(2, name);
        p_stmt.setDouble(3, age);
        p_stmt.setString(4, department);
        p_stmt.setString(5, job);
        p_stmt.setString(6, contact);
        int i = p_stmt.executeUpdate();
        if (i == 1)  {
        }System.out.println("Data Updated Successfully");
        loadDataFromDatabase();

    }catch (Exception e) {
        e.printStackTrace();
    }
}

展开
收起
祖安文状元 2020-01-04 15:54:20 1046 0
1 条回答
写回答
取消 提交回答
  • 将parameterIndex用于Statement.setString指示参数标记的词汇顺序?在查询中。所以userNo应该在最后。例如:

    public void handleUpdateAction(ActionEvent event) {
        String sql = "update users set name =?, age = ?, department=?, job=?,  contact = ? where userNo =?" ;
        try {
    
            String userNo = txt_userNo.getText();
            String name = txt_name.getText();
            double age = Double.valueOf(txt_age.getText());
            String department = txt_department.getText();
            String job = txt_job.getText();
            String contact = txt_contact.getText();
            p_stmt = con.prepareStatement(sql);
    
            p_stmt.setString(1, name);
            p_stmt.setDouble(2, age);
            p_stmt.setString(3, department);
            p_stmt.setString(4, job);
            p_stmt.setString(5, contact);
            p_stmt.setString(6, userNo);
    
            int i = p_stmt.executeUpdate();
            if (i == 1)  {
            }System.out.println("Data Updated Successfully");
            loadDataFromDatabase();
    
        }catch (Exception e) {
            e.printStackTrace();
            throw e;
        }
    }
    
    2020-01-04 15:54:35
    赞同 展开评论 打赏
问答排行榜
最热
最新

相关电子书

更多
低代码开发师(初级)实战教程 立即下载
冬季实战营第三期:MySQL数据库进阶实战 立即下载
阿里巴巴DevOps 最佳实践手册 立即下载