Python连接MySQL数据库之pymysql模块使用,,前言:python


前言:python 3.x版本连接数据库,使用的是mysql库,而python 2.x 版本是用的mysqldb库

1、安装数据库:pip install pymysql

2、连接数据库,执行sql获取返回结果 写法一:

import pymysql#连接数据库cnn = pymysql.connect(host=“你的数据库地址”, user=“用户名”,password=“密码”,database=“数据库名”,charset=“utf8”)# 使用cursor()方法获取操作游标cursor = cnn.cursor()print("Connect DB successfully!")#准备执行的sqlsql = "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!")#准备执行的sqlsql = "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!")#准备执行的sqlsql = "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模块使用

评论关闭