【问题标题】:Database query works in MySQL workbench but not when I try to run them from Java数据库查询在 MySQL 工作台中有效,但当我尝试从 Java 运行它们时无效
【发布时间】:2017-05-28 16:12:19
【问题描述】:

我正在尝试从 Java 执行 MySQL 事务。这在我的 Workbench 中有效,但是当我从 Java 执行它时,它给了我这个:你的 SQL 语法有错误;检查与您的 MySQL 服务器版本相对应的手册,以获取在“插入用户(用户名,password)值('asd','asd')附近使用的正确语法;在第 1 行设置 @userId = LAST'

这是我的查询:

 public static final String CREATE_USER = "start transaction;" +
        " Insert into User(username, `password`) values (?, ?);" +
        " set @userId = LAST_INSERT_ID();" +
        " Insert into User_Roles values (@userId, ?);" +
        " commit;";

这里是执行这个查询的代码

public static boolean createUser(UserEntity user) {
    try (Connection connection = DriverManager.getConnection(Constants.URL, Constants.DATABASE_USERNAME, Constants.DATABASE_PASSWORD)) {
        System.out.println("Database connected!");
        PreparedStatement st = connection.prepareStatement(DatabaseQuery.CREATE_USER);
        st.setString(1, user.getUsername());
        st.setString(2, user.getPassword());
        if(user.getRole().equals("User"))
            st.setInt(3, 1);
        else
            st.setInt(3, 2);
        if (st.execute())
            return true;
    } catch (SQLException e) {
        e.printStackTrace();
    }
    return false;
}

我看了这个问题1,但我没有空间问题。

【问题讨论】:

  • 你有五个陈述,而不是一个。

标签: java mysql


【解决方案1】:

[已解决]

是的,你是对的,我在同一个查询中有多个语句。

我解决它的方法是修改我的数据库 URL,以便它可以接受以分号分隔的多个查询,如下所示:

public static String URL = "jdbc:mysql://localhost/javaDb?allowMultiQueries=true";

【讨论】:

    猜你喜欢
    • 2014-04-08
    • 1970-01-01
    • 1970-01-01
    • 2016-09-04
    • 1970-01-01
    • 2014-09-29
    • 1970-01-01
    • 1970-01-01
    • 2019-10-17
    相关资源
    最近更新 更多