java mysql 更新

标签 java mysql jdbc sql-update

我在执行 java 类更新 mysql 数据库时遇到这个错误

com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: 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 'usage = 6000 where user_id = 1 and api_id = 1'
 at line 1
        at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
        at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstruct
orAccessorImpl.java:39)..

代码如下:

int u_id=1;
int a_id=1;

String url = "jdbc:mysql://localhost:3306/new_db";
String driver = "com.mysql.jdbc.Driver";
String userName = "root";
String password = "1234";
int APIusage = 0;


try {
    Class.forName(driver).newInstance();

    Connection conn = DriverManager.getConnection(url, userName, password);
    String query = "update api_consume set usage = ? where user_id = ? and api_id = ?";
    PreparedStatement preparedStmt = conn.prepareStatement(query);
    preparedStmt.setInt(1, 6000);
    preparedStmt.setInt(2, u_id);
    preparedStmt.setInt(3, a_id);

    // execute the java preparedstatement
    preparedStmt.executeUpdate();

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

能否请您查看一下,看看为什么会出现语法错误? 谢谢

最佳答案

用法 是一个 reserved word 在 MySQL 中,因此你需要引用它:

String query = "update api_consume set `usage` = ? where user_id = ? and api_id = ?";

关于java mysql 更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12315472/

相关文章:

java - 在 jTextField 中显示数据库记录

java - 获取值的键而不是获取键值?

java - 尝试使用 eclipse 从 Arduino 读取数据时收到不完整的消息?

java - 用于在 JavaFx ListView 中进行多项选择的事件监听器

java - 在 Eclipse 中通过 Hibernate 加载 MySQL 数据库时遇到问题

mysql - 是否可以从数据库创建 ruby​​-on-rails 迁移?

java - 如何在 Java servlet 的插入查询中将字符串类型转换为二进制类型

java - 尝试使用 Java 获取 Google 电子表格返回 HTTP 错误 405

php - 渴望加载在一对多关系上返回 null

python - Informix 连接速度 - Informatica PowerCenter 与 Python by JDBC