python连接mysql数据库带where条件的查询操作

#encoding=utf-8
import MySQLdb
class Sjb_data():
def __init__(self):
self.url = url

def mysql(self,sql):
db = MySQLdb.connect(host='IP地址',port = 3306,user=r'用户名',passwd='密码',db ='数据库名',charset= 'utf8')
cur = db.cursor()
cur.execute(sql) #执行sql
#data = cur.fetchone() # 使用 fetchone() 方法获取一条数据
results = cur.fetchall() #获取查询表内所有数据
for i in results:
print i #分别打印表内每一条数据
db.close() #关闭数据库

if __name__ == "__main__":
t = Sjb_data()
mysql = "SELECT * FROM qyswfx_nsrjbxx t where t.nsrsbh='%s'" %('%s的值')
t.mysql(mysql)

#刚开始sql是mysql = "SELECT * FROM qyswfx_nsrjbxx t where t.nsrsbh=%s" %('%s的值'),

#查询一直报错:_mysql_exceptions.OperationalError: (1054,"Unknown column '查询条件的值' in 'where clause'",
#在网上查了之后发现是因为where条件后面的值格式化输出的时候还是要加引号才能识别,加了之后就能正常查询到了。

猜你喜欢

转载自www.cnblogs.com/xinyibaba/p/9233228.html
今日推荐