登录  /  注册

python使用pymysql实现操作mysql

高洛峰
发布: 2017-01-10 13:31:27
原创
1228人浏览过

pymsql是python中操作mysql的模块,其使用方法和mysqldb几乎相同。但目前pymysql支持python3.x而后者不支持3.x版本。

适用环境

python版本 >=2.6或3.3

mysql版本>=4.1

安装

可以使用pip安装也可以手动下载安装。

使用pip安装,在命令行执行如下命令:

pip install PyMySQL

手动安装,请先下载。下载地址:https://github.com/PyMySQL/PyMySQL/tarball/pymysql-X.X。

其中的X.X是版本(目前可以获取的最新版本是0.6.6)。

下载后解压压缩包。在命令行中进入解压后的目录,执行如下的指令:

python setup.py install

建议使用pip安装。

使用示例

连接数据库如下:

import pymysql.cursors
  
# Connect to the database
connection = pymysql.connect(host='127.0.0.1',
               port=3306,
               user='root',
               password='zhyea.com',
               db='employees',
               charset='utf8mb4',
               cursorclass=pymysql.cursors.DictCursor)
登录后复制

也可以使用字典进行连接参数的管理,我觉得这样子更优雅一些:

import pymysql.cursors
  
config = {
     'host':'127.0.0.1',
     'port':3306,
     'user':'root',
     'password':'zhyea.com',
     'db':'employees',
     'charset':'utf8mb4',
     'cursorclass':pymysql.cursors.DictCursor,
     }
  
# Connect to the database
connection = pymysql.connect(**config)
登录后复制

插入数据:

执行sql语句前需要获取cursor,因为配置默认自动提交,故在执行sql语句后需要主动commit,最后不要忘记关闭连接:

from datetime import date, datetime, timedelta
import pymysql.cursors
  
#连接配置信息
config = {
     'host':'127.0.0.1',
     'port':3306,
     'user':'root',
     'password':'zhyea.com',
     'db':'employees',
     'charset':'utf8mb4',
     'cursorclass':pymysql.cursors.DictCursor,
     }
# 创建连接
connection = pymysql.connect(**config)
  
# 获取明天的时间
tomorrow = datetime.now().date() + timedelta(days=1)
  
# 执行sql语句
try:
  with connection.cursor() as cursor:
    # 执行sql语句,插入记录
    sql = 'INSERT INTO employees (first_name, last_name, hire_date, gender, birth_date) VALUES (%s, %s, %s, %s, %s)'
    cursor.execute(sql, ('Robin', 'Zhyea', tomorrow, 'M', date(1989, 6, 14)));
  # 没有设置默认自动提交,需要主动提交,以保存所执行的语句
  connection.commit()
  
finally:
  connection.close();
登录后复制

执行查询:

import datetime
import pymysql.cursors
  
#连接配置信息
config = {
     'host':'127.0.0.1',
     'port':3306,
     'user':'root',
     'password':'zhyea.com',
     'db':'employees',
     'charset':'utf8mb4',
     'cursorclass':pymysql.cursors.DictCursor,
     }
# 创建连接
connection = pymysql.connect(**config)
  
# 获取雇佣日期
hire_start = datetime.date(1999, 1, 1)
hire_end = datetime.date(2016, 12, 31)
  
# 执行sql语句
try:
  with connection.cursor() as cursor:
    # 执行sql语句,进行查询
    sql = 'SELECT first_name, last_name, hire_date FROM employees WHERE hire_date BETWEEN %s AND %s'
    cursor.execute(sql, (hire_start, hire_end))
    # 获取查询结果
    result = cursor.fetchone()
    print(result)
  # 没有设置默认自动提交,需要主动提交,以保存所执行的语句
  connection.commit()
  
finally:
  connection.close();
登录后复制

这里的查询支取了一条查询结果,查询结果以字典的形式返回:

从结果集中获取指定数目的记录,可以使用fetchmany方法:

result = cursor.fetchmany(2)

不过不建议这样使用,最好在sql语句中设置查询的记录总数。

获取全部结果集可以使用fetchall方法:

result = cursor.fetchall()

因为只有两条记录,所以上面提到的这两种查询方式查到的结果是一样的:

[{'last_name': 'Vanderkelen', 'hire_date': datetime.date(2015, 8, 12), 'first_name': 'Geert'}, {'last_name': 'Zhyea', 'hire_date': datetime.date(2015, 8, 21), 'first_name': 'Robin'}]
登录后复制

在django中使用

在django中使用是我找这个的最初目的。目前同时支持python3.4、django1.8的数据库backend并不好找。这个是我目前找到的最好用的。

设置DATABASES和官方推荐使用的MySQLdb的设置没什么区别:

DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'mytest',
'USER': 'root',
'PASSWORD': 'zhyea.com',
'HOST': '127.0.0.1',
'PORT': '3306',
}
}

关键是这里:我们还需要在站点的__init__.py文件中添加如下的内容:

import pymysql
pymysql.install_as_MySQLdb()

最后给大家附上pymysql实现增删改查的代码,希望大家能够喜欢

#!/usr/bin/python
#coding:gbk
import pymysql
from builtins import int
 
#将MysqlHelper的几个函数写出来
 
def connDB():               #连接数据库
  conn=pymysql.connect(host="localhost",user="root",passwd="zx69728537",db="student");
  cur=conn.cursor();
  return (conn,cur);
 
def exeUpdate(conn,cur,sql):        #更新或插入操作
  sta=cur.execute(sql);
  conn.commit();
  return (sta);
 
def exeDelete(conn,cur,IDs):        #删除操作
  sta=0;
  for eachID in IDs.split(' '):
    sta+=cur.execute("delete from students where Id=%d"%(int(eachID)));
  conn.commit();
  return (sta);
     
def exeQuery(cur,sql):           #查找操作
  cur.execute(sql);
  return (cur);
   
def connClose(conn,cur):          #关闭连接,释放资源
  cur.close();
  conn.close();
 
result=True;
print("请选择以上四个操作:1、修改记录,2、增加记录,3、查询记录,4、删除记录.(按q为退出)");
conn,cur=connDB();
number=input();
while(result):
  if(number=='q'):
    print("结束操作");
    break;
  elif(int(number)==1):
    sql=input("请输入更新语句:");
    try:
      exeUpdate(conn, cur, sql);
      print("更新成功");
    except Exception:
      print("更新失败");
      raise;
  elif(int(number)==2):
      sql=input("请输入新增语句:");
      try:
        exeUpdate(conn, cur, sql);
        print("新增成功");
      except Exception:
        print("新增失败");
        raise;
  elif(int(number)==3):
    sql=input("请输入查询语句:");
    try:
      cur=exeQuery(cur, sql);
      for item in cur:
        print("Id="+str(item[0])+" name="+item[1]);
    except Exception:
      print("查询出错");
      raise;
  elif(int(number)==4):
    Ids=input("请输入Id,并用空格隔开");
    try:
      exeDelete(conn, cur, Ids);
      print("删除成功");
    except Exception:
      print("删除失败");
      raise;
  else:
    print("非法输入,将结束操作!");
    result=False;
    break;
  print("请选择以上四个操作:1、修改记录,2、增加记录,3、查询记录,4、删除记录.(按q为退出)");
  number=input("请选择操作");
登录后复制

更多python使用pymysql实现操作mysql相关文章请关注PHP中文网!

智能AI问答
PHP中文网智能助手能迅速回答你的编程问题,提供实时的代码和解决方案,帮助你解决各种难题。不仅如此,它还能提供编程资源和学习指导,帮助你快速提升编程技能。无论你是初学者还是专业人士,AI智能助手都能成为你的可靠助手,助力你在编程领域取得更大的成就。
来源:php中文网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
关于CSS思维导图的课件在哪? 课件
凡人来自于2024-04-16 10:10:18
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2024 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号