繁体   English   中英

使用Python MySQLdb执行多表查询

[英]Executing multi-table queries with Python MySQLdb

我一直试图从两个不同的表中返回值,但似乎无法获取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()

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

你为什么用5

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM