lambda(python3.6)pymysql query exists query始终返回1

fxnxkyjh  于 2021-06-24  发布在  Mysql
关注(0)|答案(1)|浏览(415)

我试图在lambda(python3.6)中获取pymysql查询,以返回用户是否存在。我将slack用户id传递到查询中。这就是我想在mysql中检查的内容。我可以通过mysql运行相同的查询,它返回一个0,但是由于某种原因,每次我通过lambda调用这个查询时,它都会告诉我用户存在(我的数据库是空的)。我的查询是这样的:

def userExists(user):
    statement = f"SELECT EXISTS(SELECT 1 FROM slackDB.Assets WHERE userID LIKE '%{user}%')Assets"
    tempBool  = cursor.execute(statement, args=None) 
    conn.commit()
    return tempBool

以下是我正在使用的完整代码:


################################ 

# Slack Lambda handler.

################################ 

import sys
import logging
import os
import pymysql
import urllib

# Grab data from the environment.

BOT_TOKEN   = os.environ["BOT_TOKEN"]
ASSET_TABLE = os.environ["ASSET_TABLE"]
REGION_NAME = os.getenv('REGION_NAME', 'us-east-2')

DB_NAME     = "admin"
DB_PASSWORD = "somepassword"
DB_DATABASE = "someDB"
RDS_HOST    = "myslackdb.somepseudourl.us-east-2.rds.amazonaws.com"
port        = 3306

logger = logging.getLogger()
logger.setLevel(logging.INFO)

try:
    conn = pymysql.connect(RDS_HOST, user=DB_NAME, passwd=DB_PASSWORD, db=DB_DATABASE, connect_timeout=5)
    cursor = conn.cursor()
except:
    logger.error("ERROR: Unexpected error: Could not connect to MySql instance.")
    sys.exit()

# Define the URL of the targeted Slack API resource.

SLACK_URL = "https://slack.com/api/chat.postMessage"

def userExists(user):
    statement = f"SELECT EXISTS(SELECT 1 FROM slackDB.Assets WHERE userID LIKE '%{user}%')Assets"
    tempBool  = cursor.execute(statement, args=None) 
    conn.commit()
    return tempBool

def addUser(user):
    statement = f"INSERT INTO `slackDB`.`Assets` (`userID`, `money`) VALUES ('{user}', '1000')"
    tempBool  = cursor.execute(statement, args=None) 
    conn.commit()
    return tempBool

def lambda_handler(data, context):
    # Slack challenge answer.
    if "challenge" in data:
        return data["challenge"]

    # Grab the Slack channel data.
    slack_event    = data['event']
    slack_userID   = slack_event["user"]
    slack_text     = slack_event["text"]
    channel_id     = slack_event["channel"]
    slack_reply    = ""

    # Ignore bot messages.
    if "bot_id" in slack_event:
        slack_reply = ""
    else:
        # Start data sift.
        if slack_text.startswith("!networth"):
            slack_reply = "Your networth is: "
        elif slack_text.startswith("!price"):
            command,asset = text.split()
            slack_reply = f"The price of a(n) {asset} is: "
        elif slack_text.startswith("!addme"):
            if userExists(slack_userID):
                slack_reply = f"User {slack_userID} already exists"
            else:
                slack_reply = f"Adding user {slack_userID}"
                addUser(slack_userID)

        # We need to send back three pieces of information:
        data = urllib.parse.urlencode(
            (
                ("token", BOT_TOKEN),
                ("channel", channel_id),
                ("text", slack_reply)
            )
        )
        data = data.encode("ascii")

        # Construct the HTTP request that will be sent to the Slack API.
        request = urllib.request.Request(
            SLACK_URL, 
            data=data, 
            method="POST"
        )
        # Add a header mentioning that the text is URL-encoded.
        request.add_header(
            "Content-Type", 
            "application/x-www-form-urlencoded"
        )

        # Fire off the request!
        urllib.request.urlopen(request).read()

    # Everything went fine.
    return "200 OK"

我在打字!在slack中添加我,它总是告诉我用户存在。我已经打印出我的查询语句,它正在正确输入我的slack id。我已经检查了我的table,它是完全空的。我在mysql中运行了这个查询,它返回一个0。
有人有什么想法吗?我是不是在找点简单的事?任何帮助或暗示都将不胜感激。
谢谢,

a5g8bdjr

a5g8bdjr1#

我看不到 fetch 从光标。只是 execute .
以及从 execute 是受影响的行数。对于dml操作(insert/update/delete),这是有意义的。但我不会依赖受影响的行数来进行选择。
在这种情况下 SELECT EXISTS 查询要么返回一行,要么抛出一个错误。但是查询返回一行的事实并没有告诉我们关于 Assets 列。
从查询中,我们似乎要获取一行,然后确定 Assets 列包含0或1(或null)。
执行查询后,请重试 cur.fetchone 检索行。
我们还可以执行一个更简单的查询,然后使用fetch来确定是否返回了一行。

相关问题