如何在pymysql中使用多个变量
How to use multiple variables in pymysql
如何在查询中使用多个变量:
import pymysql
def get_firstname(y):
db = pymysql.connect(host="xxx.xxx.xxx.xxx",
user="xxxx",
passwd="xxxxx",
db="XXXXXXX")
cur = db.cursor()
query = "SELECT first_name FROM information WHERE x = y;"
cur.execute(query, (y))
result = str(cur.fetchone()[0])
return(result)
x = user_id
y = 1
print (get_firstname(y))
我希望能够根据我的选择将 x 更改为不同的变量。像 user_id、姓氏、电子邮件等。我数据库中的所有列。 #y 是另一个变量,代表我数据库中列的值。
例1:如果x是“user_id”,y是“1”,那么结果就是user_id1的人的名字。
Ex2:如果 x 是“email”,y 是“person@person.com”,那么结果就是电子邮件 person@person.com.
使用下面的代码:
import pymysql
def get_firstname(x, y):
db = pymysql.connect(host='xxx.xxx.xxx.xxx',
port=3306,
user='xxxx',
password='xxxxxxxx',
db='test_db')
cur = db.cursor()
query = "SELECT first_name FROM `information` WHERE %s" %(x)
final_query = query+"=%s"
#print(final_query)
cur.execute(final_query, (y,))
result = cur.fetchall()
return(result)
x = 'user_id'
y = 1
output = get_firstname(x,y)
if output:
for x in output:
print(x)[0]
Sample Inputs:
x = 'email_id'
y = 'xx@gmail.com'
或
x = 'user_id'
y = 1 // Not enclosed with single quotes
如何在查询中使用多个变量:
import pymysql
def get_firstname(y):
db = pymysql.connect(host="xxx.xxx.xxx.xxx",
user="xxxx",
passwd="xxxxx",
db="XXXXXXX")
cur = db.cursor()
query = "SELECT first_name FROM information WHERE x = y;"
cur.execute(query, (y))
result = str(cur.fetchone()[0])
return(result)
x = user_id
y = 1
print (get_firstname(y))
我希望能够根据我的选择将 x 更改为不同的变量。像 user_id、姓氏、电子邮件等。我数据库中的所有列。 #y 是另一个变量,代表我数据库中列的值。
例1:如果x是“user_id”,y是“1”,那么结果就是user_id1的人的名字。
Ex2:如果 x 是“email”,y 是“person@person.com”,那么结果就是电子邮件 person@person.com.
使用下面的代码:
import pymysql
def get_firstname(x, y):
db = pymysql.connect(host='xxx.xxx.xxx.xxx',
port=3306,
user='xxxx',
password='xxxxxxxx',
db='test_db')
cur = db.cursor()
query = "SELECT first_name FROM `information` WHERE %s" %(x)
final_query = query+"=%s"
#print(final_query)
cur.execute(final_query, (y,))
result = cur.fetchall()
return(result)
x = 'user_id'
y = 1
output = get_firstname(x,y)
if output:
for x in output:
print(x)[0]
Sample Inputs:
x = 'email_id'
y = 'xx@gmail.com'
或
x = 'user_id'
y = 1 // Not enclosed with single quotes