【问题标题】:Executing multi-table queries with Python MySQLdb使用 Python MySQLdb 执行多表查询
【发布时间】:2017-10-07 21:06:26
【问题描述】:

我一直在尝试从两个不同的表中返回值,但似乎无法让 c.execute(query) 函数返回我想要的值。目前我的代码将返回第一个 c.fetchone()[0],但第二个 fetchone()[5] 给出一个错误,它超出范围,这意味着它可能仍在尝试从我的“客户”表中获取数据它没有 6 列。我不认为我完全理解 MySQLdb 的工作原理,这很神奇,但找不到任何好的多表查询示例。这是我的代码 sn-p 下面!谢谢!

c, conn = connection()

            #check if already exists
            x = c.execute("SELECT * FROM clients WHERE email = (%s)", (thwart(email),))

            if int(x) > 0:
                flash("That email already has an account, please try a new email or sign in.")
                return render_template('register.html', form=form)
            else:
                c.execute("INSERT INTO clients (email, phone, password) VALUES (%s, %s, %s)", (thwart(email), thwart(phone), thwart(password)))
                c.execute("SELECT cid FROM clients WHERE email = (%s)", (thwart(email),))
                clientcid = c.fetchone()[0]
                c.execute("INSERT INTO cpersonals (first_name, last_name, address, zip) VALUES (%s, %s, %s, %s)", (thwart(first_name), thwart(last_name), thwart(address), czip))
                c.execute("SELECT reg_date FROM cpersonals WHERE cid = (%s)", (clientcid,))
                reg_date = c.fetchone()[5]
                rating = c.execute("SELECT rating FROM clients WHERE email = (%s)", (thwart(email),))
                conn.commit()
                flash("Thanks for registering!")
                c.close()
                conn.close()

【问题讨论】:

    标签: python mysql mysql-python fetchall


    【解决方案1】:

    您的查询是SELECT reg_date FROM cpersonals ...。您只选择一列。 fetchone()[5] 失败的原因是,获取的记录中没有第 6 列。尝试用0 代替5

    你为什么使用5

    【讨论】:

    • 我的理解是fetchone()[5]是从最后一条SQL查询语句返回的元组中选择第6列。执行 fetchone()[0] 将返回客户端 ID 号,因为这是存储 ID 号的列。
    • 有问题的列号是您的选择语句中从左到右的列顺序。听起来您正试图将其与您正在查询的表中的列位置相关联。表列号与该问题无关。该查询仅包含一列,因此您可以获取字段[0],没有其他字段,因为没有其他字段。
    • 我现在明白了,成功了!我现在觉得使用 fetchone()[0] 并不是在元组中提取一个数据字段的最佳方式,但我尝试这样做 reg_date = c.execute("SELECT reg_date FROM cpersonals WHERE cid = (%s)", (clientcid,)) ,但我一直将值“1”输入到 reg_date。大概是因为它正在获取该集合中有多少变量。
    • 如果我的回答解决了你的问题,请点击绿色复选标记。
    • 非常感谢您的帮助!如果您知道比我使用的方法更好的方法,那么最后一条评论也是一个问题?
    猜你喜欢
    • 2011-06-04
    • 1970-01-01
    • 2010-11-01
    • 2019-05-09
    • 2021-09-10
    • 1970-01-01
    • 2012-12-04
    • 1970-01-01
    • 2012-02-29
    相关资源
    最近更新 更多