Docker 部署mysql + python操作

1.部署mysql

  • 拉取MySQL 镜像
默认拉去最新版本
docker pull mysql
或者指定版本
docker pull mysql:5.7
  • 查看本地镜像
docker images
  • 运行容器
设置 MySQL 服务 root 用户的密码
MYSQL_ROOT_PASSWORD=123456 设置密码
MYSQL_ALLOW_EMPTY_PASSWORD  允许空密码
MYSQL_RANDOM_ROOT_PASSWORD   随机密码

–privileged=true:提升容器内权限
-v /home/mysql/conf/my.cnf:/etc/mysql/mysql.conf.d/mysqld.cnf:映射配置文件
-v /home/mysql/data:/var/lib/mysql:映射数据目录

# 挂载数据
docker run --name mysql --privileged=true -p 3306:3306 -v /home/mysql/data:/var/lib/mysql -e MYSQL_ROOT_PASSWORD='123456' -d mysql:5.7

# 挂载配置和数据
docker run --name mysql5.7  --privileged=true   \
-p 3306:3306   \
-v /home/mysql/conf/my.cnf:/etc/mysql/mysql.conf.d/mysqld.cnf   \
-v /home/mysql/data:/var/lib/mysql   \
-e  MYSQL_ROOT_PASSWORD="123456" -d mysql:5.7

### 2、Python操作

 - pymysql 连接

```python
# config配置连接地址
    DATABASE_HOST = '127.0.0.1'
    DATABASE_PORT = 3306
    DATABASE_USER = 'root'
    DATABASE_PASSWORD = '123456'
    DATABASE_DB = 'test_test'
    DATABASE_CHARSET = 'utf8'
# 封装公共方法连接
import pymysql
from flask import g, current_app


def get_db():
    if 'db' not in g:
        g.db = pymysql.connect(host=current_app.config['DATABASE_HOST'], port=current_app.config['DATABASE_PORT'],
                               user=current_app.config['DATABASE_USER'],
                               password=current_app.config['DATABASE_PASSWORD'],
                               db=current_app.config['DATABASE_DB'], charset=current_app.config['DATABASE_CHARSET'])

    return g.db
  • 使用
# 导入get_db方法
db = get_db()

# insert
 try:
    cursor = db.cursor(cursor=cursors.DictCursor)
    cursor.execute('insert into  person value(%s,%s,%s)',
                           (params['id'], params['name'], params['age']
                           ))
 except Exception as e:
     db.rollback()
     return False
 else:
     db.commit()
     return True


# update
try:
    cursor = db.cursor(cursor=cursors.DictCursor)
    cursor.execute('update person set name=%s,age=%s where id=%s',
                           (params['name'],  params['age']
                           ))
 except Exception as e:
     db.rollback()
     return False
 else:
     db.commit()
     return True

# get
cursor = db.cursor(cursor=cursors.DictCursor)
cursor.execute("select * from person where id=%s", group_id)
# cursor.execute("select * from person")
person_info = cursor.fetchone()
# person_list = cursor.fetchall()
return person_info 

# delete
try:
    cursor = db.cursor(cursor=cursors.DictCursor)
    cursor.execute("delete from person where id=%s", id)
except Exception as e:
    db.rollback()
    return False
else:
    db.commit()
    return True
Logo

权威|前沿|技术|干货|国内首个API全生命周期开发者社区

更多推荐