当前位置:Gxlcms > 数据库问题 > Python连接MySQL数据库之pymysql模块使用

Python连接MySQL数据库之pymysql模块使用

时间:2021-07-01 10:21:17 帮助过:5人阅读

pymysql #连接数据库 cnn = pymysql.connect(host=“你的数据库地址”, user=“用户名”,password=“密码”,database=“数据库名”,charset=“utf8”) # 使用cursor()方法获取操作游标 cursor = cnn.cursor() print("Connect DB successfully!") #准备执行的sql sql = "SELECT * FROM `uc_alias` where type=1 and id = 110137" try: # 执行SQL语句 cursor.execute(sql) # 获取所有记录列表 results = cursor.fetchall() for row in results: id = row[0] type = row[1] appid = row[2] info = row[3] token = row[4] ext = row[5] unionid = row[7] state = row[8] ctime = row[9] atime = row[10] # 打印结果 print("id=%s,type=%s,appid=%s,info=%s,token=%s,ext=%s,unionid=%s,state=%s,ctime=%s,atime=%s" %(id, type, appid, info, token,ext, unionid, state, ctime,atime)) except: print("Error: unable to fecth data") # 关闭光标对象 cursor.close() #关闭数据库连接 cnn.close()

运行的结果:

技术图片

3、执行aql获取单条数据结果,写法二

import pymysql

#连接数据库
cnn = pymysql.connect(host=“你的数据库地址”, user=“用户名”,password=“密码”,database=“数据库名”,charset=“utf8”)

# 使用cursor()方法获取操作游标
cursor = cnn.cursor()
print("Connect DB successfully!")

#准备执行的sql
sql = "SELECT * FROM `uc_alias` where type=1 and id = 110137"
cursor.execute(sql)
#获取单条查询的结果
ret = cursor.fetchone()

# 关闭光标对象
cursor.close()
#关闭数据库连接
cnn.close()
print(ret)

运行结果只有条:

技术图片

3、执行aql获取多条数据结果

import pymysql

#连接数据库
cnn = pymysql.connect(host=“你的数据库地址”, user=“用户名”,password=“密码”,database=“数据库名”,charset=“utf8”)

# 使用cursor()方法获取操作游标
cursor = cnn.cursor()
print("Connect DB successfully!")

#准备执行的sql
sql = "SELECT * FROM `uc_alias` where ctime between 1496739700 and 1496739720"
cursor.execute(sql)
#获取多条查询的结果
ret = cursor.fetchall()

# 关闭光标对象
cursor.close()
#关闭数据库连接
cnn.close()
print(ret)

运行结果有多条:

技术图片

Python连接MySQL数据库之pymysql模块使用

标签:nec   alias   state   install   fetchall   col   数据库   between   charset   

人气教程排行