- import pymysql
- conn = pymysql.connect(host='127.0.0.1', user='root', passwd="xxx", db='mysql')
- cur = conn.cursor()
- cur.execute("SELECT Host,User FROM user")
- for r in cur:
- print(r)
- cur.close()
- conn.close()
4、peewee
- import peewee
- from peewee import *
- db = MySQLDatabase('jonhydb', user='john', passwd='megajonhy')
- class Book(peewee.Model):
- author = peewee.CharField()
- title = peewee.TextField()
- class Meta:
- database = db
- Book.create_table()
- book = Book(author="me", title='Peewee is cool')
- book.save()
- for book in Book.filter(author="me"):
- print(book.title)
写原生 SQL 的过程异常繁琐,代码反复,没有面向对象思维,继而出生了很多封装 wrapper 包和 ORM 框架,ORM 是 Python 对象与数据库关系表的一种映射关系,有了 ORM 你不再须要写 SQL 语句。进步了写代码的速度,同时兼容多种数据库体系,如sqlite, mysql、postgresql,付出的价值可能就是机能上的一些损掉。如不雅你对 Django 自带的 ORM 熟悉的话,那么 peewee的进修成本几乎为零。它是 Python 中是最风行的 ORM 框架。
- pip install peewee
一个例子
官方文档:http://docs.peewee-orm.com/en/latest/peewee/installation.html
【编辑推荐】
- 比来租房有点烦!技恋人若何用Python找到称心如意的“小窝”?
- 我是若何零基本开端能写Python爬虫的
- 若何用Python编写信息收集之阁下名收集脚本?
- 17个新手常见Python运行时缺点
- 我用Python爬了一个零售网站,分析了一千多种葡萄酒!
5、SQLAlchemy
如不雅想找一种既支撑原生 SQL,又支撑 ORM 的对象,那么 SQLAlchemy 是最好的选择,它异常接近 Java 中的 Hibernate 框架。
- from sqlalchemy import create_engine
- from sqlalchemy.orm import sessionmaker
- from sqlalchemy_declarative import Address, Base, Person
- class Address(Base):
推荐阅读
开辟者大年夜赛路演 | 12月16日,技巧立异,北京不见不散 本次分享重要环绕Go在数据库中心件应用这方面展开;起首会聊一下法度榜样开辟的需求,具领会参考Go的特点是否知足这些需求;接下来>>>详细阅读
本文标题:用Python连接MySQL的几种姿势
地址:http://www.17bianji.com/lsqh/39659.html
1/2 1

网友点评
精彩导读
科技快报
品牌展示