我在运行此sql语句时遇到问题.如果我在mysql中运行它,它工作正常,但在java中我得到此错误:
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
Run Code Online (Sandbox Code Playgroud)
数据库有一个id(pk)autogenerated,varchar,int,varchar;
有人能帮我吗?
int i = statement.executeUpdate("INSERT INTO sala values('','"+ nume.getText() + "', "+ Integer.parseInt(capacitate.getText())+ ", '" + sunet.getText()+"'");
Run Code Online (Sandbox Code Playgroud)
不要只是尝试通过根据adarshr的答案调整SQL来修复此代码.你有一个基本的安全问题,你现在应该修复.由于直接在SQL中包含用户数据,您对SQL注入攻击持开放态度.
您应该使用a PreparedStatement,在SQL中将参数声明为占位符,然后单独给定值.究竟你将如何做到这一点,将取决于你的JDBC提供者,但它会看起来事情是这样的:
// TODO: Fix the column names, and close the statement in a try/finally block
PreparedStatement pst = conn.prepareStatement(
"INSERT INTO sala (nume, capacitate, sunet) VALUES (?, ?, ?)");
pst.setString(1, nume.getText());
pst.setInt(2, Integer.parseInt(capacitate.getText()));
pst.setString(3, sunet.getText());
pst.executeUpdate();
Run Code Online (Sandbox Code Playgroud)
请注意,如果您可以capacite以不需要整数解析的方式获得,那就很好.否则,请考虑使用NumberFormat哪个更适合语言环境.另请注意,我已将列名添加到SQL中,以便在架构更改时使其更加健壮.
您尚未关闭查询.
int i = statement.executeUpdate("INSERT INTO sala values('','"+ nume.getText() + "', "+ Integer.parseInt(capacitate.getText())+ ", '" + sunet.getText()+"')");
^
Run Code Online (Sandbox Code Playgroud)
但比所有这更,您必须使用PreparedStatement如乔恩以下建议.
| 归档时间: |
|
| 查看次数: |
1393 次 |
| 最近记录: |