为什么设置 SQL 变量会产生错误?

Why is setting SQL variable is creating an error?

以下 SQL 语句正在创建错误消息: "Message: Fatal error encountered during command execution." "Inner exception: Parameter '@LastUserID' must be defined."

如果我直接使用 LAST_INSERT_ID() 而不是 LastUserID,它在这样执行时总是 returns 零(因此在第二次插入时失败)。

我没有发现我的语法与 mySQL 文档中的语法不同。

有人能帮帮我吗?

string Query = @"INSERT INTO login (" +
                                    "LOGIN_EMAIL," +
                                    "LOGIN_PASSWORD," +
                                    "LOGIN_SALT," +
                                    "LOGIN_LAST_LOGIN_DATE," +
                                    //         "LOGIN_LAST_LOGIN_LOCATION," +
                                    "LOGIN_ACCOUNT_STATUS," +
                                    "LOGIN_LOGIN_ATTEMPTS," +
                                    "LOGIN_CREATED_DATE) " +
                                "VALUES (" +
                                    "@Parameter2," +
                                    "@Parameter3," +
                                    "@Parameter4," +
                                    "@Parameter5," +
                                    //                                        "@Parameter6," +
                                    "@Parameter6," +
                                    "@Parameter7," +
                                    "@Parameter8); " +
                                "SET @LastUserID = LAST_INSERT_ID(); " + 
                                "INSERT INTO user_role (" +
                                    "USER_ROLE_USER_ID," +
                                    "USER_ROLE_ROLE," +
                                    "USER_ROLE_STATUS," +
                                    "USER_ROLE_CREATED_DATE) " +
                                "SELECT " +
                                    "@LastUserID," +
                                    "@Parameter9," +
                                    "@Parameter10," +
                                    "@Parameter11 " +
                                "FROM dual WHERE NOT EXISTS (SELECT USER_ROLE_USER_ID FROM user_role " +
                                "WHERE USER_ROLE_USER_ID = @LastUserID AND USER_ROLE_ROLE = @Parameter9)";

                    MySqlCommand oCommand = new MySqlCommand(Query, oMySQLConnecion);

                oCommand.Transaction = tr;

简单修复:将“$LastUserID”替换为“$'LastUserID'”。哲学使人与众不同。

创建一个程序,首先执行插入操作,缓存最后插入的 ID,执行另一个插入操作,然后让它用布尔值打印出您的参数(无论最后一次插入操作是否有效)。这样你就可以正确调试它了。

一般来说,您应该避免连接字符串来生成 sql-commands,否则您可能会遇到包含意外字符的参数或被 injection.

击中的问题