SQL 未命名参数语法
Posted
技术标签:
【中文标题】SQL 未命名参数语法【英文标题】:SQL unnamed parameter syntax 【发布时间】:2020-11-23 08:04:24 【问题描述】:我检查了两次,为什么会这样?我有正确数量的未命名参数,列名是正确的。
*
您的 SQL 语法有错误;检查手册 对应于您的 MariaDB 服务器版本以获取正确的语法 to 在'附近使用? , ? , ? , ? ,?,? )' 在第 1 行
public void adiciona(Libro libro)
try
String sql = "insert into libro (isbn, titulo, precio, stock, cod_categoria, cod_editorial) values ( ? , ? , ? , ? ,?,? )";
String sqlQuery = "select count(*) from libro where isbn = " + libro.getIsbn();
sentencia = connection.createStatement();
resultSet = sentencia.executeQuery(sqlQuery);
resultSet.next();
if (resultSet.getInt(1) == 0)
try (PreparedStatement preparedStatement = connection.prepareStatement(sql))
preparedStatement.setInt(1, libro.getIsbn());
preparedStatement.setString(2, libro.getTitulo());
preparedStatement.setDouble(3, libro.getPrecio());
preparedStatement.setInt(4, libro.getStock());
preparedStatement.setInt(5, libro.getCod_categoria());
preparedStatement.setInt(6, libro.getCod_editorial());
retorno = sentencia.executeUpdate(sql);
preparedStatement.execute();
catch (SQLIntegrityConstraintViolationException e)
System.out.printf("error duplicado: %s\n",e);
catch (SQLException e)
throw new RuntimeException(e);
else if(retorno> 0) System.out.println("added");
else System.out.println("no added.");
catch (SQLException e)
throw new RuntimeException(e);
【问题讨论】:
【参考方案1】:您可能编辑了问题,尝试了一些方法。一个干净的版本是:
public void adiciona(Libro libro)
// Not needed:
String sqlQuery = "select count(*) from libro where isbn = ?";
try (PreparedStatement sentencia = connection.createStatement(sqlQuery))
sentencia.setInt(libro.getIsbn());
try (ResultSet resultSet = sentencia.executeQuery())
if (resultSet.next() && sentencia.getLong(1) > 0L)
return;
catch (SQLException e)
throw new RuntimeException(e);
String sql = "insert into libro (isbn, titulo, precio, stock, cod_categoria, cod_editorial) "
+ "values (?, ?, ?, ?, ?, ?)";
try (PreparedStatement preparedStatement = connection.prepareStatement(sql))
preparedStatement.setInt(1, libro.getIsbn());
preparedStatement.setString(2, libro.getTitulo());
preparedStatement.setDouble(3, libro.getPrecio());
preparedStatement.setInt(4, libro.getStock());
preparedStatement.setInt(5, libro.getCod_categoria());
preparedStatement.setInt(6, libro.getCod_editorial());
int retorno = preparedStatement.executeUpdate();
if (retorno > 0)
System.out.println("added")
else
System.out.println("not added.");
catch (SQLIntegrityConstraintViolationException e)
System.out.printf("error duplicado: %s\n", e);
throw new RuntimeException(e);
catch (SQLException e2)
throw new RuntimeException(e2);
【讨论】:
@EmanuelMosby 注意&& sentencia.getLong(1) > 0L
我稍后在不需要的代码中添加。【参考方案2】:
在retorno = sentencia.executeUpdate(sql);
尝试删除参数sql
【讨论】:
以上是关于SQL 未命名参数语法的主要内容,如果未能解决你的问题,请参考以下文章
使用可变参数但使用命名参数调用函数的 Scala 语法是啥?
Flutter TextSelection.collapsed:未定义命名参数“offset”