转载本文章请标明作者和出处
本文出自《Darwin的程序空间》
vlog
- 时间:2020年03月08日-2020年03月09日 ——————晚上三个小时
- 学习方式:菜鸟教程,博客,百度
- 完成内容:使用pymysql对mysql数据库进行增删改查,并封装一个数据库操作类,最后写一个脚本往数据库导入100W的数据
- 博客目的:总结归纳,当然要能帮助其他刚学习Python的童鞋,不胜荣幸
- 人物:一个心血来潮学习Python的JAVA程序员
正文
操作mysql
安装mysql
首先想操作数据库,必须得现在本机或者远程云服务器上安装一个MYSQL,这里笔者是在本地起了一个docker,跑了一个mysql5.7的容器;
这类的教程网上很多,这里就不多做声明,如果读者没有学过docker也可以使用传统的安装方式,mysql的安装还是很简单的,傻瓜式安装即可;
安装后我们可以使用navicat连接上即算成功;
安装pymysql
-
使用如下命令
pip install PyMySQL
-
如果这种方式行不通的话,可以现在tar.gz包,解压后使用python setup.py install命令安装pymysql模块
使用pymysql简单的操作数据库
-
操作步骤
- 首先我们要使用connect函数指定ip、用户名、密码、数据库来获取数据库连接对象;
- 然后使用数据库连接对象获取游标;(可以指定游标查询获取数据的类型,默认为元组,这里可以指定为字典conn.cursor(cursor=cursors.DictCursor))
- 使用游标来执行原生的sql语句(用惯了SpringDataJpa的我,好久没有整过原生的sql了),这里会返回影响的数据库数据的条数
- 使用游标的fetch系列的方法来获取结果;
- 如果对数据库有修改操作,需要使用连接对象提交事务;
- 关闭游标和连接的资源,调用close方法;
-
代码(使用pymysql获取数据库版本和创建数据库的demo)
- 查询数据库版本
from pymysql import * # 获取数据库的连接 conn = connect("192.168.100.145", "root", "123", "JD") # 获取有表对象 cursors = conn.cursor() # 执行查询数据库版本的SQL语句 cursors.execute("select version()") # 获取一条结果 version = cursors.fetchone() # 打印结果 print("Database version is %s" % version) # 关闭游标 cursors.close() # 关闭数据的连接 conn.close()
- 创建数据库
from pymysql import * conn = connect("192.168.100.145", "root", "123", "JD") cursors = conn.cursor() sql = "CREATE TABLE EMPLOYEE ( \ FIRST_NAME CHAR(20) NOT NULL, \ LAST_NAME CHAR(20), \ AGE INT, \ SEX CHAR(1),\ INCOME FLOAT )" cursors.execute(sql) cursors.close() conn.close()
- 查询数据库版本
使用pymysql完成增删改查四大基本操作
- 增
from pymysql import *
conn = connect(“192.168.100.145”, “root”, “123”, “JD”)
cursors = conn.cursor()
SQL 插入语句
-
增
from pymysql import * conn = connect("192.168.100.145", "root", "123", "JD") cursors = conn.cursor() # SQL 插入语句 sql = "INSERT INTO EMPLOYEE(FIRST_NAME, \ LAST_NAME, AGE, SEX, INCOME) \ VALUES ('%s', '%s', %s, '%s', %s)" % \ ('Mac', 'Mohan', 20, 'M', 2000) try: # 执行sql语句 cursors.execute(sql) # 执行sql语句 conn.commit() except Exception as res: # 发生错误时回滚 conn.rollback() print("error %s" % res) cursors.close() conn.close()
-
查
from pymysql import * conn = connect("192.168.100.145", "root", "123", "JD") cursors = conn.cursor() # SQL 查询语句 sql = "SELECT * FROM EMPLOYEE \ WHERE INCOME > %s" % "1000" try: # 执行SQL语句 cursors.execute(sql) # 获取所有记录列表 results = cursors.fetchall() for row in results: print(type(row)) # <class 'tuple'> fname = row[0] lname = row[1] age = row[2] sex = row[3] income = row[4] # 打印结果 print("fname=%s,lname=%s,age=%s,sex=%s,income=%s" % \ (fname, lname, age, sex, income)) except: print("Error: unable to fetch data") cursors.close() conn.close()
-
改
from pymysql import * conn = connect("192.168.100.145", "root", "123", "JD") cursors = conn.cursor() # SQL 更新语句 sql = "UPDATE EMPLOYEE SET AGE = AGE + 1 WHERE SEX = '%c'" % ('M') try: # 执行SQL语句 row = cursors.execute(sql) print("一共影响了%d行" % row) # 提交到数据库执行 conn.commit() except Exception as res: # 发生错误时回滚 conn.rollback() print("error %s" % res) cursors.close() conn.close()
-
删
from pymysql import * conn = connect("192.168.100.145", "root", "123", "JD") cursors = conn.cursor() # 使用cursor()方法获取操作游标 cursor = conn.cursor() # SQL 删除语句 sql = "DELETE FROM EMPLOYEE WHERE AGE > %s" % "20" try: # 执行SQL语句 cursor.execute(sql) # 提交修改 conn.commit() except Exception as res: # 发生错误时回滚 conn.rollback() print("error %s" % res) cursors.close() conn.close()
封装数据库操作对象
-
with as用法
在Python中使用try…except…finally的语句太过啰嗦,不符合Python语言编程的哲学,果然,经过往上搜索之后,发现了一个简单的语法with…as语句在创建类的时候,在内部实现__enter__方法,with语句一开始就会执行这个方法,
再实现__exit__方法,退出with代码块的时候会自动执行这个方法。- 例子(来源于网络)
class A: def __enter__(self): print('with语句开始') return self # 返回self就是把这个对象赋值给as后面的变量 def __exit__(self, exc_type, exc_val, exc_tb): print('with语句结束') with A() as f: print('IG牛批') print(f) print('IG真的牛批') 结果: with语句开始 IG牛批 <__main__.A object at 0x0000027B4D1596D8> with语句结束 IG真的牛批
- 例子(来源于网络)
-
然后我们就可以使用这个语法和面向对象的知识,来封装一个数据库操作的类
from pymysql import * class DB(object): def __init__(self, ip="192.168.100.145", username="root", password="123", database_name="JD"): self.conn = connect(ip, username, password, database_name) self.cursor = self.conn.cursor(cursor=cursors.DictCursor) def __enter__(self): """ 这个方法的返回值将被赋值给as关键字后面的变量 """ return self.cursor def __exit__(self, exc_type, exc_val, exc_tb): """ 当with后面的代码块全部被执行完之后,将调用前面返回对象的__exit__()方法 """ self.conn.commit() self.cursor.close() self.conn.close() if __name__ == '__main__': with DB() as db: db.execute("select version()") version = db.fetchone() print(type(version)) print(version)
百万数据导入
-
代码
from pymysql import * import time conn = connect("192.168.2.89", "root", "123", "console_hy") cursor = conn.cursor() start = time.time() i = 0 try: while i < 1000000: sql = "INSERT INTO EMPLOYEE(FIRST_NAME, \ LAST_NAME, AGE, SEX, INCOME) \ VALUES ('%s', '%s', %s, '%s', %s)" % \ ('Mac', 'Mohan', 20, 'M', i) # 执行sql语句 cursor.execute(sql) i += 1 # 执行sql语句 conn.commit() except Exception as res: # 发生错误时回滚 conn.rollback() print("error %s" % res) cursor.close() conn.close() end = time.time() print("100W数据用时%ds" % (int(end) - int(start)))
-
耗时
- 100W数据用时395s