码迷,mamicode.com
首页 > 数据库 > 详细

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

时间:2019-03-18 11:43:31      阅读:276      评论:0      收藏:0      [点我收藏+]

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

前言: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!")

#准备执行的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   

原文地址:https://www.cnblogs.com/guo2733/p/10551077.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!