Python中使用MySQL数据提取结构化数据

    技术2022-07-11  71

    前言

    MySQLdb是MySQL C接口上开发的Python API。 假设你已经对Python开发有一定对了解。

    安装MySQLdb

    pip install MySQLdb

    但遗憾的是,你发现,出现了下面的错误:

    Could not find a version that satisfies the requirement MySQLdb (from versions: )No matching distribution found for MySQLdb

    几个意思?原来是没有这么一个包,找了原因发现MySQLdb只只支持到python3.4,因此,如果你是python3.5+的用户,那肯定找不到这么一个包,那如何是好?

    其实,python3.5以上的用户,可以安装另外一个mysql驱动:PyMySQL

    pip3 install PyMySQL

    使用

    import pymysql

    确保你的数据库存在以下数据库和表:

    数据库名称:test数据表:student字段:id,name,age

    数据库连接

    import pymysql db = pymysql.connect('localhost', 'root', 'root@12345', 'test') cursor = db.cursor()

    INSERT 操作

    简单的插入信息操作

    def insert(): db = pymysql.connect('localhost', 'root', 'root@12345', 'test') cursor = db.cursor() print('INSERT 操作') sql = """insert into student(name,age) values('猪八戒','20')""" cursor.execute(sql) db.commit() db.close()

    READ 操作

    fetchone(): 该方法获取下一个查询结果集。结果集是一个对象fetchall(): 接收全部的返回结果行.rowcount: 这是一个只读属性,并返回执行execute()方法后影响的行数。 def red(): db = pymysql.connect('localhost', 'root', 'root@12345', 'test') cursor = db.cursor() sql = """select * from student""" cursor.execute(sql) db.commit() results = cursor.fetchall() for row in results: fid = row[0] fname = row[1] fage = row[2] print('id=%s,name=%s,age=%s' % (fid, fname, fage)) db.close()

    UPDATE 和 DELETE操作和插入操作是一样的,都是写sql。

    特殊点

    封装sql类型操作

    class my_db(): def __init__(self, host='localhost', port=3306, user='root', pwd='root@12345', db=''): self.conn = pymysql.connect(host, db=db, user=user, passwd=pwd) self.cur = self.conn.cursor() def __enter__(self): return self.cur def __exit__(self, exc_type, exc_val, exc_tb): self.conn.commit() self.cur.close() self.conn.close() if __name__ == '__main__': with my_db(db='test') as db: sql = """select count(1) as count from student""" db.execute(sql) count = db.fetchone() print(count[0])

    pymysql.Connect()参数说明

    host(str): MySQL服务器地址 port(int): MySQL服务器端口号 user(str): 用户名 passwd(str): 密码 db(str): 数据库名称 charset(str): 连接编码 connection对象支持的方法 cursor() 使用该连接创建并返回游标 commit() 提交当前事务 rollback() 回滚当前事务 close() 关闭连接 cursor对象支持的方法 execute(op) 执行一个数据库的查询命令 fetchone() 取得结果集的下一行 fetchmany(size) 获取结果集的下几行 fetchall() 获取结果集中的所有行 rowcount() 返回数据条数或影响行数 close() 关闭游标对象

    总结

    以上就是python 操作数据库的一般用法,依据项目的不同,你还可以使用ORM框架,如 GINO或者SQLAlchemy

    Processed: 0.008, SQL: 9