mysql 在sql查询中传递变量时出错

gwbalxhn  于 2023-05-16  发布在  Mysql
关注(0)|答案(1)|浏览(189)

我试图用Python在SQL查询中传递一个变量。但是查询中传递了其他变量。

PostNewUniqueVal = 0
                        BETA__ = True
                        while BETA__:
                            RandNumm = random.randrange(100000000000,99999999999999)
                            if RandNumm in AllPostID:
                                continue
                            else:
                                PostNewUniqueVal = RandNumm
                                BETA__ = False

                        AddPost_connection2 = mysql.connector.connect(host=HOSTNAME,user=USER,password=PASSWD,database=DB)
                        AddPost_cursor2 = AddPost_connection2.cursor()

                        PostContent = PostText_entry.get("0.0", "end")
                        PostingUserID = USER_DET['USER_ID']
                        PostSno = ALPHA2__[-1]+1
                        PostIDNew = PostNewUniqueVal

                        AddPost_cursor2.execute(f'INSERT INTO `posts`(`sno`, `user_id`, `post_id`, `post_content`) VALUES ({PostSno},{PostingUserID},{PostIDNew},"{PostContent}")')

                        AddPost_connection2.commit()
                        AddPost_connection2.close()
                        AddPost_frame.destroy()

例如:如果PostNewUniqueVal的值为2,则在查询中传递7

0md85ypi

0md85ypi1#

您的代码包含以下内容,并使用标记来解释它的作用:

# Initialize a variable to store a new unique value for a post ID
PostNewUniqueVal = 0 

# Set a flag to indicate that the loop should continue running
BETA__ = True

# Keep generating random numbers until a unique one is found
while BETA__:
    # Generate a random number between 100000000000 and 99999999999999
    RandNumm = random.randrange(100000000000,99999999999999)
    
    # Check if the generated number is already in the list of all post IDs
    if RandNumm in AllPostID:
        # If it is, continue generating new numbers
        continue
    else:
        # If it is not, set the new unique value for the post ID and exit the loop
        PostNewUniqueVal = RandNumm
        BETA__ = False

# Set the new post ID to the unique value that was found
PostIDNew = PostNewUniqueVal

因此,代码通过生成随机数来生成新的唯一帖子ID,直到找到一个不在所有帖子ID列表中的帖子ID。然后将新的帖子ID设置为该唯一值。
也就是说,你可以初始化一个值为2,但是在SQL查询中插入7,因为PostIDNew是由随机数建立的。
要避免SQL注入并传递正确的参数,请使用参数化查询。例如

AddPost_cursor2.execute('INSERT INTO `posts`(`sno`, `user_id`, `post_id`, `post_content`) VALUES (%s,%s,%s,%s)', (PostSno, PostingUserID, PostIDNew, PostContent))

这会将值传递给execute方法,该方法将处理值的转义和引用,以防止SQL注入。

相关问题