Python如何链接MySQL?
时间:2021-09-10 16:36:57
手机看文章
扫描二维码
随时随地手机看文章
[导读]在python程序里,如何链接MySQL数据库?连接MYSQL需要3步1、安装必须先安装MySQL驱动。和PHP不一样,Python只默认安装了SQLite的驱动。最常用的包是MySQLdb但是用easy_install安装很困难。对于Window用户,你可以获取MySQLdb的...
在python程序里,如何链接MySQL数据库?
连接MYSQL需要3步
1、安装
必须先安装MySQL驱动。和PHP不一样,Python只默认安装了SQLite的驱动。最常用的包是MySQLdb但是用easy_install安装很困难。对于Window用户,你可以获取MySQLdb的exe。对于Linux,可以下载python-mysqldb(可以用sudo apt-get install python-mysqldb命令直接在命令行下载)对于Mac用户,可以用Macport下载MySQLdb2、使用
装完之后重启。这样做可以减少问题。然后就像用其他包一样:#!/usr/bin/pythonimportMySQLdbdb =MySQLdb.connect(host="localhost",# your host, usually localhostuser="john",# your usernamepasswd="megajonhy",# your passworddb="jonhydb")# name of the data base# you must create a Cursor object. It will let# you execute all the queries you needcur = db.cursor()# Use all the SQL you likecur.execute("SELECT * FROM YOUR_TABLE_NAME")# print all the first cell of all the rowsfor row in cur.fetchall():print row[0]
3、高级用法
一旦你知道它是如何工作的,你可能想用ORM来避免手动写入SQL,来把表变成Python对象。Python中最有名的ORM叫做SQLAlchemy(强烈推荐)最近又在Python里发现了一个好东西:peewee。它是个非常轻巧的ORM,非常容易安装和使用。一些小项目和独立app都可以使用它,像SQLLAlchemy或者Django用在这里有点小题大做了:import peeweefrom peewee import*db =MySQLDatabase('jonhydb', user='john',passwd='megajonhy')classBook(peewee.Model):author = peewee.CharField()title = peewee.TextField()classMeta:database = dbBook.create_table()book =Book(author="me", title='Peewee is cool')book.save()for book inBook.filter(author="me"):print book.titlePeeweeis cool
pip install peewee)不需要别的的操作。安装非常简单。END
来源:Python编程学习圈版权归原作者所有,如有侵权,请联系删除。
▍






