使用Python MySQLdb执行多表查询

时间:2017-10-07 21:06:27

标签: python mysql mysql-python fetchall

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

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()

1 个答案:

答案 0 :(得分:1)

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

您为什么使用5