Python pymysql模块对数据库Mysql,Mariadb的操作

一、基础命令

1.pymysql模块

通过pip安装pymysql模块

pip是pypi(python package index)的安装命令,pypi是python语言的软件仓库

官方网站http://pypi.python.org

 

2.安装pymysql模块和mariadb

mariadb是mysql的设计者开发的开源数据库

  1. [root@localhost ~]# yum -y install gcc
  2. [root@localhost ~]# pip3 install pymysql

在安装之前,可以加载国内站点下载

  1. [root@localhost ~]# mkdir ~/.pip
  2. [root@localhost ~]# vim ~/.pip/pip.conf
  3. [global]
  4. index-url = http://pypi.douban.com/simple/
  5. [install]
  6. trusted-host=pypi.douban.com

 

3.连接数据库

创建连接是访问数据库的第一步

  1. import pymysql
  2. conn = pymysql.connect(
  3. host='127.0.0.1',                          #连接ip
  4. port=3306,                                   #端口号
  5. user='root',                                  #数据库用户名
  6. passwd='密码',                       #数据库密码
  7. db='表名',                                    #数据库名
  8. charset='utf8'                              #设置了数据库的字符集
  9. )

 

4.游标

游标(cursor)就是游动的标识

通俗的说,一条sql取出对应n条结果的句柄,游标可以指向这n个句柄的任意一个,沿着游标可以一次取出一行

curor=conn.cursr()

 

5.插入数据

对数据库表做修改操作(插入,修改,删除),必须要提交事务,commit

在进行插入操作前,必须先获取游标对象curor=conn.cursr()

  1. insert1 = "INSERT INTO 表名(字段) VALUES(%s)"
  2. cursor.execute(insert1, (值))                                       # execute执行insert语句
  3. conn.commit()                                                             # 将更新提交到数据库

也可以一次提交多条记录,使用一个列表

  1. insert1 = "INSERT INTO 表名(字段1,字段2) VALUES(%s, %s)"
  2. data = [(1, 'abc'), (3, 'def')]  
  3. cursor.executemany(insert1, data)                             #  executemany执行insert语句
  4. conn.commit()   

 

6.查询数据

可以从表中取出一条,多条或者全部记录

  1. sql1="select * from 表名"
  2. cur.execute(sql1)
  3. result=cur.fetchone()                        #查找一条
  4. print (result)
  5. result=cur.fetchmany(2)                   #查找多条,2代表查找2条
  6. print (result)
  7. result=cur.fetchall()                          #查找所有
  8. print (result)

 

7.删除数据

  1. sql="delete from 表名 where id=%s"
  2. result=cur.execute(sql,(1))                     #使用游标变量执行execute删除字段id为1的字段
  3. conn.commit()

 

8.修改数据

  1. sql="update 表名 set 字段1=%s where 字段2=%s"
  2. result=cur.execute(sql,('abc',1))                     #使用游标变量执行execute更新字段id为1的字段
  3. conn.commit()

 

二、实验1-向表中插入数据

步骤一:PyMySQL安装

1) 安装gcc,有些软件包是C的源码

  1. [root@localhost ~]# yum install -y gcc
  2. 已加载插件:fastestmirror, langpacks
  3. dvd | 3.6 kB 00:00
  4. Loading mirror speeds from cached hostfile
  5. 匹配 gcc-4.8.5-16.el7.x86_64 的软件包已经安装。正在检查更新。
  6. 无须任何处理

2)为了加速下载,可以使用国内开源镜像站点

  1. [root@localhost ~]# mkdir ~/.pip
  2. [root@localhost ~]# vim ~/.pip/pip.conf
  3. [global]
  4. index-url = http://pypi.douban.com/simple/
  5. [install]
  6. trusted-host=pypi.douban.com

3)安装pymysql

  1. [root@localhost ~]# pip3 install pymysql

 

步骤二:安装mariadb-server

  1. [root@localhost ~]# yum install –y mariadb-server
  2.  
  3. ....
  4.  
  5. 已安装:
  6.         mariadb-server.x86_64 1:5.5.56-2.el7
  7.  
  8. 作为依赖被安装:
  9.         mariadb.x86_64 1:5.5.56-2.el7
  10.         perl-DBD-MySQL. x86_64 0:4.023-5.el7
  11.  
  12. 完毕!
  13. [root@localhost ~]# systemctl start mariadb
  14. [root@localhost ~]# systemctl enable mariadb
  15. [root@localhost ~]# mysqladmin password 123

 

步骤三:创建数据库

1)创建数据库

  1. [root@localhost ~]# mysql -uroot -p123   
  2. MariaDB [(none)]> CREATE DATABASE DB1 DEFAULT CHARSET 'utf8';
  3. Query OK, 1 row affected (0.00 sec)

2)创建部门表

部门表字段:部门ID、部门名称

  1. MariaDB [(none)]> USE DB1;
  2. Database changed
  3. MariaDB [tedu]> CREATE TABLE departments(dep_id INT PRIMARY KEY, dep_name VARCHAR(20));
  4. Query OK, 0 rows affected (0.04 sec)

3)创建员工表

员工表字段:员工编号、姓名、出生日期、部门ID、电话号码、email、引用外键id

  1. MariaDB [tedu]> CREATE TABLE employees (emp_id INT PRIMARY KEY, emp_name VARCHAR(20) NOT NULL, birth_date DATE, phone CHAR(11), email VARCHAR(50), dep_id INT, FOREIGN KEY(dep_id) REFERENCES departments(dep_id));
  2. Query OK, 0 rows affected (0.05 sec)

4)创建工资表

工资表字段:auto_id、员工编号、日期、基本工资、奖金、工资总和

  1. MariaDB [tedu]> CREATE TABLE salary(auto_id INT AUTO_INCREMENT PRIMARY KEY, date DATE, emp_id INT, basic INT, awards INT, FOREIGN KEY(emp_id) REFERENCES employees(emp_id));
  2. Query OK, 0 rows affected (0.05 sec)

 

步骤四:向departments表插入数据

1)新建insert_data.py文件,编写代码如下:

  1. [root@localhost day10]# vim insert_data.py
  2.  
  3. import pymysql
  4. #连接数据库
  5. conn = pymysql.connect(
  6. host='127.0.0.1',                               #连接ip
  7. port=3306,                                        #端口号
  8. user='root',                                        #数据库用户名
  9. passwd='123',                                   #数据库密码
  10. db='DB1',                                          #数据库名
  11. charset='utf8'                                    #设置了数据库的字符集
  12. )
  13. #创建游标
  14. cursor = conn.cursor()                                             
  15. #向部门表departments中插入数据
  16. insert1 = "INSERT INTO departments(dep_id, dep_name) VALUES(%s, %s)"
  17. result = cursor.execute(insert1, (1, '人事部'))        # execute执行insert语句
  18. #将更新提交到数据库
  19. conn.commit()    
  20. #关闭游标
  21. cursor.close()
  22. #关闭数据库连接
  23. conn.close()

2)执行insert_data.py文件:

  1. [root@localhost day10]# python3 insert_data.py

3)登录mariadb查看结果:

  1. MariaDB [tedu]>> select * from departments;
  2. +--------+-----------+
  3. | dep_id | dep_name |
  4. +--------+-----------+
  5. | 1 | 人事部 |
  6. +--------+-----------+
  7. 1 row in set (0.00 sec)

4) 向部门表departments中插入数据还可以用如下方法:

  1. #以上insert_data.py文件第3步可用如下代码替换:
  2.  
  3. insert1 = "INSERT INTO departments(dep_id, dep_name) VALUES(%s, %s)"
  4. data = [(2, '运维部'), (3, '开发部')]
  5. cursor.executemany(insert1, data)

mariadb查看结果如下:

  1. MariaDB [tedu]>> select * from departments;
  2. +--------+-----------+
  3. | dep_id | dep_name |
  4. +--------+-----------+
  5. | 1 | 人事部 |
  6. | 2 | 运维部 |
  7. | 3 | 开发部 |
  8. +--------+-----------+
  9. 3 rows in set (0.01 sec)

 

步骤五:向employees表插入数据

1)新建insert_emp.py文件,编写代码如下:

  1. [root@localhost day10]# vim insert_emp.py
  2.  
  3. import pymysql
  4. #连接数据库
  5. conn = pymysql.connect(
  6. host='127.0.0.1',                                #连接ip
  7. port=3306,                                         #端口号
  8. user='root',                                         #数据库用户名
  9. passwd='123',                                    #数据库密码
  10. db='DB1',                                           #数据库名
  11. charset='utf8'                                     #设置了数据库的字符集
  12. )
  13. #创建游标
  14. cursor = conn.cursor()
  15. #向部门表employees中插入数据
  16. insert1 = "INSERT INTO employees(emp_id, emp_name, birth_date,phone, email, dep_id) VALUES(%s, %s, %s, %s, %s, %s)"
  17. result = cursor.execute(insert1, (1, '王君', '2018-9-30','15678789090', 'wj@163.com', 3))       
  18. #将更新提交到数据库
  19. conn.commit()    
  20. #关闭游标
  21. cursor.close()
  22. #关闭数据库连接
  23. conn.close()

2)执行insert_emp.py文件:

  1. [root@localhost day10]# python3 insert_emp.py

3)登录mariadb查看结果:

  1. MariaDB [tedu]>> select * from employees;
  2. +--------+----------+------------+-------------+------------+--------+
  3. | emp_id | emp_name | birth_date | phone | email | dep_id |
  4. +--------+----------+------------+-------------+------------+--------+
  5. | 1 | 王君 | 2018-09-30 | 15678789090 | wj@163.com | 3 |
  6. +--------+----------+------------+-------------+------------+--------+
  7. 1 row in set (0.00 sec)

4) 向部门表employees中插入数据还可以用如下方法:

  1. #以上insert_emp.py文件第3步可用如下代码替换:
  2.  
  3. insert1 = "INSERT INTO employees (dep_id, dep_name) VALUES(%s, %s)"
  4. data = [(2, '运维部'), (3, '开发部')]
  5. cursor.executemany(insert1, data)

mariadb查看结果如下:

  1. MariaDB [tedu]>> select * from departments;
  2. +--------+----------+------------+-------------+------------+--------+
  3. | emp_id | emp_name | birth_date | phone | email | dep_id |
  4. +--------+----------+------------+-------------+------------+--------+
  5. | 1 | 王君 | 2018-09-30 | 15678789090 | wj@163.com | 3 |
  6. | 2 | 李雷 | 2018-09-30 | 15678789090 | wj@163.com | 2 |
  7. | 3 | 张美 | 2018-09-30 | 15678789090 | zm@163.com | 1 |
  8. +--------+----------+------------+-------------+------------+--------+
  9. 3 rows in set (0.00 sec)

 

步骤六:向salary表插入数据

1)新建insert_sal.py文件,编写代码如下:

  1. [root@localhost day10]# vim insert_sal.py
  2.  
  3. import pymysql
  4. 1)连接数据库
  5. conn = pymysql.connect(
  6. host='127.0.0.1',                            #连接ip
  7. port=3306,                                     #端口号
  8. user='root',                                     #数据库用户名
  9. passwd='123',                                #数据库密码
  10. db='DB1',                                       #数据库名
  11. charset='utf8'                                 #设置了数据库的字符集
  12. )
  13. #创建游标
  14. cursor = conn.cursor()
  15. #向部门表salary中插入数据
  16. insert2 = "INSERT INTO salary(date, emp_id,basic, awards) VALUES(%s, %s, %s, %s)"
  17. data = [('2018-9-30', 2, 1000, 2000), ('2018-9-30', 3, 3000, 6000),('2018-9-30', 1, 8000, 9000)]
  18. cursor.executemany(insert2, data)
  19. #将更新提交到数据库
  20. conn.commit()    
  21. #关闭游标
  22. cursor.close()
  23. #关闭数据库连接
  24. conn.close()

2)执行insert_sal.py文件:

  1. [root@localhost day10]# python3 insert_sal.py

3)登录mariadb查看结果:

  1. MariaDB [tedu]>> select * from salary;
  2. +---------+------------+--------+-------+--------+
  3. | auto_id | date | emp_id | basic | awards |
  4. +---------+------------+--------+-------+--------+
  5. | 1 | 2018-09-30 | 2 | 1000 | 2000 |
  6. | 2 | 2018-09-30 | 3 | 3000 | 6000 |
  7. | 3 | 2018-09-30 | 1 | 8000 | 9000 |
  8. +---------+------------+--------+-------+--------+
  9. 3 rows in set (0.01 sec)

 

 

三、实验2-创建表 

 

  1. 创建employees表
  2. 创建部门表
  3. 创建salary表
  4. 表间创建恰当的关系

2.2 步骤

实现此案例需要按照如下步骤进行。

步骤一:SQLAlchemy安装

注意:sqlalchemy可以连接各种数据库

 
  1. [root@serwang ~]# pip3 install sqlalchemy
  2. Collecting sqlalchemy
  3. Downloading http://pypi.doubanio.com/packages/aa/cc/48eec885d81f7260b07d
  4. 961b3ececfc0aa82f7d4a8f45ff997e0d3f44ba/SQLAlchemy-1.2.11.tar.gz (5.6MB)
  5. ...
  6. ...
  7. Installing collected packages: sqlalchemy
  8. Running setup.py install for sqlalchemy ... done
  9. Successfully installed sqlalchemy-1.2.11
  10. You are using pip version 9.0.1, however version 18.0 is available.
  11. You should consider upgrading via the 'pip install --upgrade pip' command.

步骤二:为SQLAlchemy创建数据库

 
  1. MariaDB [tedu]> CREATE DATABASE tarena DEFAULT CHARSET 'utf8';

步骤三:创建部门表,创建dbconn.py文件,编写如下代码:

1) 创建连接到数据库的引擎

 
  1. [root@localhost day10]# vim dbconn.py
  2.  
  3. #!/usr/bin/env python3
  4.  
  5. from sqlalchemy import create_engine
  6.  
  7. # 创建连接到数据库的引擎
  8. engine = create_engine(
  9.         #指定数据库、用户名、密码、连接到哪台服务器、库名等信息
  10. 'mysql+pymysql://root:tedu.cn@localhost/tarena?charset=utf8',
  11. encoding='utf8',
  12. echo=True    #终端输出
  13. )        

2)创建ORM映射,生成ORM映射所需的基类

 
  1. from sqlalchemy.ext.declarative import declarative_base
  2.  
  3. Base = declarative_base()

3)自定义映射类,创建部门表

 
  1. from sqlalchemy import Column, String, Integer
  2.  
  3. class Departments(Base): # 必须继承于Base
  4. __tablename__ = 'departments' # 库中的表名
  5. # 每个属性都是表中的一个字段,是类属性
  6. dep_id = Column(Integer, primary_key=True)    #Integer整数类型,primary_key主键
  7. # String字符串类型,nullable非空约束,unique唯一性约束
  8.      dep_name = Column(String(20), nullable=False, unique=True)
  9.  
  10. def __str__(self):
  11. return '[部门ID:%s, 部门名称:%s]' % (self.dep_id, self.dep_name)
  12. if __name__ == '__main__':
  13. # 在数据库中创建表,如果库中已有同名的表,将不会创建
  14. Base.metadata.create_all(engine)

4)测试脚本执行,生成部门表

 
  1. [root@localhost day10]# python3 dbconn.py    #成功生成部门表

5)进入数据库查看结果

 
  1. #登录数据库
  2. [root@localhost day10]# mysql -uroot -ptedu.cn    
  3. Welcome to the MariaDB monitor. Commands end with ; or \g.
  4. Your MariaDB connection id is 5
  5. Server version: 5.5.56-MariaDB MariaDB Server
  6.  
  7. Copyright (c) 2000, 2017, Oracle, MariaDB Corporation Ab and others.
  8.  
  9. Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
  10. #查看数据库表
  11. MariaDB [(none)]> use tarena;
  12. Reading table information for completion of table and column names
  13. You can turn off this feature to get a quicker startup with -A
  14.  
  15. Database changed
  16. MariaDB [tarena]> show tables;
  17. +------------------+
  18. | Tables_in_tarena |
  19. +------------------+
  20. | departments |
  21. +------------------+
  22. 1 row in set (0.00 sec)
  23.  
  24.  
  25. MariaDB [tarena]> show create table departments;
  26. +-------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
  27. | Table | Create Table |
  28. +-------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
  29. | departments | CREATE TABLE `departments` (
  30. `dep_id` int(11) NOT NULL AUTO_INCREMENT,
  31. `dep_name` varchar(20) NOT NULL,
  32. PRIMARY KEY (`dep_id`),
  33. UNIQUE KEY `dep_name` (`dep_name`)
  34. ) ENGINE=InnoDB DEFAULT CHARSET=utf8 |
  35. +-------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
  36. 1 row in set (0.00 sec)

步骤四:创建员工表,在dbconn.py文件中添加如下数据:

1)创建员工表

 
  1. from sqlalchemy import ForeignKey    导入外键
  2.  
  3. class Employees(Base): # 必须继承于Base
  4. __tablename__ = 'employees' # 库中的表名
  5.      # 每个属性都是表中的一个字段,是类属性
  6. emp_id = Column(Integer, primary_key=True)     #Integer整数类型,primary_key主键
  7. name = Column(String(20), nullable=False) # String字符串类型,nullable非空约束
  8. gender = Column(String(6))
  9. phone = Column(String(11))
  10. email = Column(String(50))
  11. dep_id = Column(Integer, ForeignKey('departments.dep_id'))    #与departments中dep_id做外键关联
  12.  
  13. def __str__(self):
  14. return '员工:%s' % self.name

4)测试脚本执行,生成员工表

 
  1. [root@localhost day10]# python3 dbconn.py    #成功生成员工表

5)进入数据库查看结果

 
  1. #登录数据库
  2. [root@localhost day10]# mysql -uroot -ptedu.cn    
  3. Welcome to the MariaDB monitor. Commands end with ; or \g.
  4. Your MariaDB connection id is 5
  5. Server version: 5.5.56-MariaDB MariaDB Server
  6.  
  7. Copyright (c) 2000, 2017, Oracle, MariaDB Corporation Ab and others.
  8.  
  9. Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
  10. #查看数据库表
  11. MariaDB [(none)]> use tarena;
  12. Reading table information for completion of table and column names
  13. You can turn off this feature to get a quicker startup with -A
  14.  
  15. Database changed
  16. MariaDB [tarena]> show tables;
  17. +------------------+
  18. | Tables_in_tarena |
  19. +------------------+
  20. | departments |
  21. | employees |
  22. +------------------+
  23. 2 rows in set (0.00 sec)

步骤五:创建工资表,在dbconn.py文件中添加如下数据:

1)创建工资表

 
  1. from sqlalchemy import Date    导入外键
  2.  
  3. class Employees(Base): # 必须继承于Base
  4. __tablename__ = 'employees' # 库中的表名
  5.      # 每个属性都是表中的一个字段,是类属性
  6. emp_id = Column(Integer, primary_key=True)     #Integer整数类型,primary_key主键
  7. name = Column(String(20), nullable=False) # String字符串类型,nullable非空约束
  8. gender = Column(String(6))
  9. phone = Column(String(11))
  10. email = Column(String(50))
  11. dep_id = Column(Integer, ForeignKey('departments.dep_id'))    #与departments中dep_id做外键关联
  12.  
  13. def __str__(self):
  14. return '员工:%s' % self.name
  15.  
  16. class Salary(Base): # 必须继承于Base
  17. __tablename__ = 'salary' # 库中的表名
  18. auto_id = Column(Integer, primary_key=True) #Integer整数类型,primary_key主键
  19. date = Column(Date)    #导入日期
  20. emp_id = Column(Integer, ForeignKey('employees.emp_id')) #与employees中emp_id做外键关联
  21. basic = Column(Integer)        #基本工资
  22. awards = Column(Integer)    #奖金

4)测试脚本执行,生成员工表

 
  1. [root@localhost day10]# python3 dbconn.py    #成功生成工资表

5)进入数据库查看结果

 
  1. #登录数据库
  2. [root@localhost day10]# mysql -uroot -ptedu.cn    
  3. Welcome to the MariaDB monitor. Commands end with ; or \g.
  4. Your MariaDB connection id is 5
  5. Server version: 5.5.56-MariaDB MariaDB Server
  6.  
  7. Copyright (c) 2000, 2017, Oracle, MariaDB Corporation Ab and others.
  8.  
  9. Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
  10. #查看数据库表
  11. MariaDB [(none)]> use tarena;
  12. Reading table information for completion of table and column names
  13. You can turn off this feature to get a quicker startup with -A
  14.  
  15. Database changed
  16. MariaDB [tarena]> show tables;
  17. +------------------+
  18. | Tables_in_tarena |
  19. +------------------+
  20. | departments |
  21. | employees |
  22. | salary |
  23. +------------------+
  24. 3 rows in set (0.00 sec)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值