为什么这个SQL在MySQL中而不是通过Eclipse执行?

时间:2012-02-06 13:34:49

标签: mysql jdbc

我在MYSQL中有以下表格:

  CREATE TABLE 't001_prospeccao' (
  'pro_id' bigint(20) NOT NULL AUTO_INCREMENT,
  'pro_cliente' bigint(20) NOT NULL,
  'pro_produto' bigint(20) NOT NULL,
  'pro_status' int(11) DEFAULT NULL,
  'pro_vlr_entabulado' double DEFAULT NULL,
  'pro_vlr_contratado' double DEFAULT NULL,
  'pro_vlr_utilizado' double DEFAULT NULL,
  'pro_obs' varchar(255) DEFAULT NULL,
  'pro_dt_visita' datetime DEFAULT NULL,
  'pro_dt_originacao' datetime DEFAULT NULL,
  'pro_protocolo' double DEFAULT NULL,
  'pro_correio' double DEFAULT NULL,
  'pro_dt_status' datetime DEFAULT NULL,
  'pro_funci' bigint(20) DEFAULT NULL,
  PRIMARY KEY ('pro_id'),
  UNIQUE KEY 'id_UNIQUE' ('pro_id')
) ENGINE=InnoDB AUTO_INCREMENT=13 DEFAULT CHARSET=latin1

以下INSERT语句,它在MySQL控制台中正常执行:

INSERT INTO t001_prospeccao (pro_cliente,pro_produto) VALUES (123456789,111)

但是,在Eclipse中运行此代码时,会出现错误:

 String sql = "INSERT INTO t001_prospeccao (pro_cliente,pro_produto) VALUES (?,?);";

            PreparedStatement stmt = connection.prepareStatement(sql);

            try {
                stmt.setLong(1, p.getCliente().getMci());
                stmt.setLong(2, p.getProduto().getCod());

                stmt.execute(sql);

            } catch (SQLException e) {
                throw new RuntimeException(e);
            } finally {
                stmt.close();
            }

错误:

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '?,?)' at line 1

来自stmt对象的数据:

INSERT INTO t001_prospeccao (pro_cliente,pro_produto) VALUES (123456789,111)

我该怎么办?提前谢谢。

1 个答案:

答案 0 :(得分:4)

您正在使用Statement.execute(String),您应该使用PreparedStatement.execute()方法:

stmt.execute(sql);

那一行应该是:

stmt.execute();