【问题标题】:java.sql.SQLException: No value especified for parameter 3 Java + Mysqljava.sql.SQLException:没有为参数 3 Java + Mysql 指定值
【发布时间】:2015-11-12 02:45:13
【问题描述】:

我是巴西人,我正在尝试在数据库 MySQL 上进行批处理。

但是错误

“java.sql.SQLException:没有为参数 3 指定值”

坚持。

public ClienteCRUD(String nome, String cpf, String endereco, String cidade, String uf, String cep) throws SQLException {

        String[] str = {nome, cpf, endereco, cidade, uf, cep};

        String url = "jdbc:mysql://localhost/vendas";
        String sql = "insert into cliente (id_cliente, nomeCliente, enderecoCliente, cidade, cep, uf, cpf) values (?,?,?,?,?,?,?);";
        try (Connection con = DriverManager.getConnection(url, "root", "fabiio2");
        PreparedStatement stm = con.prepareStatement(sql)) {
            for (int i = 0; i < str.length; i++) {
                if (i == 0) {
                    stm.setInt(1, i + 4);
                    stm.setString(2, str[i]);
                }
                else {
                    stm.setString(i + 2, str[i]);
                }
                stm.addBatch();
            }
            stm.executeBatch();
    }

    }

我的数据库包含七列,其中第一列是自动分配的。

对不起,我是 Java 新手。

我指望你的帮助。

【问题讨论】:

    标签: java mysql parameters prepared-statement batch-processing


    【解决方案1】:
        public ClienteCRUD(String nome, String cpf, String endereco, String cidade, String uf, String cep) throws SQLException {
                String[] str = {nome, cpf, endereco, cidade, uf, cep};
                String url = "jdbc:mysql://localhost/vendas";
                String sql = "insert into cliente (id_cliente, nomeCliente, enderecoCliente, cidade, cep, uf, cpf) values (?,?,?,?,?,?,?)";
                try (Connection con = DriverManager.getConnection(url, "root", "fabiio2");
                PreparedStatement stm = con.prepareStatement(sql)) {
    
                //for a sql complete parameter
                for (int i = 0; i < str.length; i++) {
                    if (i == 0) {
                         stm.setInt(1, i + 4);
                         stm.setString(2, str[i]);
                    }
                    else {
                         stm.setString(i + 2, str[i]);
                    }
                }
                // to move this 
                stm.addBatch();
                stm.executeBatch();            
              }
            }
    

    【讨论】:

    • 谢谢!有效!你能解释为什么“add.batch”在“for”之外吗?我认为在每个循环中“for”都有一个“批处理”指令来组装整个过程。再次感谢您!
    猜你喜欢
    • 1970-01-01
    • 2017-06-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-02
    • 2020-03-16
    相关资源
    最近更新 更多