温欣爸比

  • 主页
  • Alfred Workflow
  • 《Vim 练级手册》
  • 常用命令
  • 代码笔记
  • 合辑
  • 在线工具
所有文章 友链 关于我

温欣爸比

  • 主页
  • Alfred Workflow
  • 《Vim 练级手册》
  • 常用命令
  • 代码笔记
  • 合辑
  • 在线工具

Python 使用 PyMySQL 操作 Mysql 数据库

2018-03-19

Python 使用 PyMySQL 操作 Mysql 数据库



  • 下载
  • 连接数据库
    • 使用 URI 创建连接
  • 操作数据库
    • 插入数据
    • 查询数据
  • 完整 demo

下载

1
$ sudo pip install PyMySQL

连接数据库

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author: wxnacy(wxnacy@gmail.com)

import pymysql.cursors
conn = pymysql.connect(
host = 'localhost',
port = 3306,
user = 'root',
password = 'passwd'
db = 'your_db'
charset = 'utf8mb4',
cursorclass = pymysql.cursors.DictCursor
)

使用 URI 创建连接

创建连接非常简单,但是配置在项目中却不方便,如果数据信息使用 URI 就简单了很多,这需要 urllib 模块的配合

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author: wxnacy(wxnacy@gmail.com)

import pymysql.cursors
from urllib.parse import urlparse

URI = 'mysql+pymysql://root:wxnacy@127.0.0.1:3306/study?charset=utf8mb4'
URL_CONFIG = urlparse(URI)

conn = pymysql.connect(
host = URL_CONFIG.hostname,
port = URL_CONFIG.port,
user = URL_CONFIG.username,
password = URL_CONFIG.password,
db = URL_CONFIG.path[1:],
charset = 'utf8mb4',
cursorclass = pymysql.cursors.DictCursor
)

注意地址模式需要使用 mysql+pymysql

操作数据库

插入数据

1
2
3
4
cursor = conn.cursor()
cursor.execute('insert into book (name) values (%s)', ['wxnacy'])
conn.commit()
cursor.close()

查询数据

1
2
3
4
5
6
cursor = conn.cursor()
cursor.execute('select * from book where name = %s', ['wxnacy'])
conn.commit()
res = cursor.fetchall()
cursor.close()
print(res) # [{"id": 1, "name": "wxnacy"}]

完整 demo

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author: wxnacy(wxnacy@gmail.com)

import pymysql.cursors
from urllib.parse import urlparse

URI = 'mysql+pymysql://root:wxnacy@127.0.0.1:3306/study?charset=utf8mb4'
URL_CONFIG = urlparse(URI)
print(URL_CONFIG)

class BaseDB(object):
@classmethod
def create_conn(cls):
'''创建mysql链接'''
return pymysql.connect(
host=URL_CONFIG.hostname,
port=URL_CONFIG.port,
user=URL_CONFIG.username,
password=URL_CONFIG.password,
db=URL_CONFIG.path[1:],
charset='utf8mb4',
cursorclass=pymysql.cursors.DictCursor
)

@classmethod
def query(cls, sql, params):
"""
查询操作
:param sql:
:param params:
:return:
"""
conn = cls.create_conn()
try:
cursor = conn.cursor()

cursor.execute(sql, params)
conn.commit()
result = cursor.fetchall()
cursor.close()
return result
except BaseException as e:
app.logger.error(traceback.format_exc())
return []
finally:
conn.close()

@classmethod
def execute(cls, sql, params):
"""
更新操作
:param sql:
:param params:
:return:
"""
conn = cls.create_conn()
try:
cursor = conn.cursor()

result = cursor.execute(sql, params)
conn.commit()
cursor.close()
return result
except BaseException as e:
app.logger.error(traceback.format_exc())
return False
finally:
conn.close()

if __name__ == "__main__":
sql = 'select * from user'
res = BaseDB.query(sql, [])
print(res)
最近更新
Alfred Workflow 命令行帮助工具
最近热读
Go 判断数组中是否包含某个 item
Vim 高级功能 vimgrep 全局搜索文件
办理北京工作居住证的一些细节
Go 语法错误:Non-declaration statement outside function body
Mac 电脑查看字体文件位置
扫码关注公众号,或搜索公众号“温欣爸比” 及时获取我的最新文章
赏

谢谢你请我喝咖啡

支付宝
微信
  • python
修改 HTMLTestRunner.py 可以在 Python3 运行
Python 获取 class 名字
  1. 1. 下载
  2. 2. 连接数据库
    1. 2.1. 使用 URI 创建连接
  3. 3. 操作数据库
    1. 3.1. 插入数据
    2. 3.2. 查询数据
  4. 4. 完整 demo
© 2017 - 2022 温欣爸比 京ICP备15062634号 总访问量3531次 访客数3483人次 本文总阅读量3次
Hexo Theme Yilia by Litten
  • 所有文章
  • 友链
  • 关于我

tag:

  • python
  • flask
  • javascript
  • docker
  • 工具
  • openresty
  • 微信
  • java
  • hexo
  • 杂谈
  • vim
  • git
  • mysql
  • http
  • linux
  • mac
  • tmux
  • ssh
  • 算法
  • 开发
  • node
  • 杂文
  • jinja2
  • maven
  • spring
  • 北京
  • 生活
  • springboot
  • react
  • shell
  • graphql
  • iterm
  • expect
  • nginx
  • sqlalchemy
  • html
  • electron
  • vagrant
  • elastic
  • 宝贝
  • ansible
  • css
  • jquery
  • go
  • markdown
  • awk
  • redis
  • leetcode
  • zsh
  • 漫威
  • ssr
  • android
  • ffmpeg
  • chrome
  • vmware
  • youtube
  • windows
  • jupyter
  • excel
  • jq
  • Mac
  • Homebrew
  • mongo
  • py2
  • HomeBrew
  • movie
  • nodejs

    缺失模块。
    1、请确保node版本大于6.2
    2、在博客根目录(注意不是yilia根目录)执行以下命令:
    npm i hexo-generator-json-content --save

    3、在根目录_config.yml里添加配置:

      jsonContent:
        meta: false
        pages: false
        posts:
          title: true
          date: true
          path: true
          text: false
          raw: false
          content: false
          slug: false
          updated: false
          comments: false
          link: false
          permalink: false
          excerpt: false
          categories: false
          tags: true
    

  • Guru99
每天看书
每天背单词
每天一篇
写写代码
听听周杰伦
爱爱老婆