Python3 MySQL 数据库连接

Python3 MySQL 数据库连接 - PyMySQL 驱动

 参考教程https://www.runoob.com/python3/python3-mysql.html

 以及PyMySQL文档https://pymysql.readthedocs.io/en/latest/modules/cursors.html

上一章讲解了创建用户和授权。本章根据参考教程,了解如何用python的包连接mysql数据库,并对数据进行操作。

前提:

  • 创建了用户testuser, 并授权。
  • 创建了testdb数据库。并创建了表employee
  • EMPLOYEE表字段为 FIRST_NAME, LAST_NAME, AGE, SEX 和 INCOME。
  • ⚠️需要安装pymysql包:  $ python3 -m pip install PyMySQL
mysql> create table employee(
    -> first_name varchar(20),
    -> last_name varchar(20),
    -> age int,
    -> sex enum("man", 'woman'),
    -> income decimal(10,2));

创建临时文件linshi.py: 打开数据库,关闭数据库。

import pymysql

db = pymysql.connect(host='localhost',user= 'testuser', password="", db='testdb')

# 创建一个游标对象
cursor = db.cursor()

cursor.execute("select version();")

data = cursor.fetchone()

print("database version %s" % data) db.close()

执行脚本输出: database version 8.0.18

创建数据库表

import pymysql

db = pymysql.connect(host='localhost',user= 'testuser', password="", db='testdb')

# 创建一个游标对象
cursor = db.cursor()

cursor.execute("drop table if exists employee;")

sql = """CREATE TABLE EMPLOYEE (
         FIRST_NAME  CHAR(20) NOT NULL,
         LAST_NAME  CHAR(20), AGE INT, SEX CHAR(1), INCOME FLOAT )"""  cursor.execute(sql) cursor.execute("desc employee") data = cursor.fetchall() for i in range(0, len(data)): print(data[i]) db.close()

⚠️:

  1. cursor对象的方法有很多fetchall()返回一个tuple。
  2. 一定要关闭数据库。

python mysql各类驱动简介

python版本早期用jmysqlLdb或叫做mysql-python,但年久失修。

于是出现了:mysqlclient,完全兼容mysqlldb,支持python3和2。

又出现了pymysql,是纯python打造,接口和pyhon-mysql兼容,并且安装方便,支持2,3。git✨5.6k

各类ORM框架:

因为,原生的sql写起来麻烦所以诞生了很多封装wrapper包和orm框架。提高了写代码的速度,同时兼容多类数据库,付出的代价是性能上的一些损失。

例如:

  1. peewee小的orm框架,git✨是7.1k。https://github.com/coleifer/peewee
  2. sqlalchemy, 在编程领域使用广泛,借助pymysql等第三方库。因此既支持原生sql也支持orm。git✨只1.7k, 开发活跃

猜你喜欢

转载自www.cnblogs.com/chentianwei/p/12103298.html
今日推荐