Python如何链接MySQL
在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下载MySQLdb
2. 使用
装完之后重启。这样做可以减少问题。
然后就像用其他包一样:
#!/usr/bin/python
importMySQLdb
db =MySQLdb.connect(host="localhost",# your host, usually localhost
user="john",# your username
passwd="megajonhy",# your password
db="jonhydb")# name of the data base
# you must create a Cursor object. It will let
# you execute all the queries you need
cur = db.cursor()
# Use all the SQL you like
cur.execute("SELECT * FROM YOUR_TABLE_NAME")
# print all the first cell of all the rows
for row in cur.fetchall():
print row[0]
还有很多用法和选项,我这里只举了一个基本的例子。
3. 高级用法
一旦你知道它是如何工作的,你可能想用ORM来避免手动写入SQL,来把表变成Python对象。Python中最有名的ORM叫做SQLAlchemy(强烈推荐)
最近又在Python里发现了一个好东西:peewee。它是个非常轻巧的ORM,非常容易安装和使用。一些小项目和独立app都可以使用它,像SQLLAlchemy或者Django用在这里有点小题大做了:
import peewee
from peewee import*
db =MySQLDatabase('jonhydb', user='john',passwd='megajonhy')
classBook(peewee.Model):
author = peewee.CharField()
title = peewee.TextField()
classMeta:
database = db
Book.create_table()
book =Book(author="me", title='Peewee is cool')
book.save()
for book inBook.filter(author="me"):
print book.title
Peeweeis cool
按上边操作即可运行,除了peewee(
pip install peewee
)不需要别的的操作。安装非常简单。文章转载:Python编程学习圈
(版权归原作者所有,侵删)
(版权归原作者所有,侵删)
点击下方“阅读原文”查看更多
关键词
用户
链接
问题
命令
最新评论
推荐文章
作者最新文章
你可能感兴趣的文章
Copyright Disclaimer: The copyright of contents (including texts, images, videos and audios) posted above belong to the User who shared or the third-party website which the User shared from. If you found your copyright have been infringed, please send a DMCA takedown notice to [email protected]. For more detail of the source, please click on the button "Read Original Post" below. For other communications, please send to [email protected].
版权声明:以上内容为用户推荐收藏至CareerEngine平台,其内容(含文字、图片、视频、音频等)及知识版权均属用户或用户转发自的第三方网站,如涉嫌侵权,请通知[email protected]进行信息删除。如需查看信息来源,请点击“查看原文”。如需洽谈其它事宜,请联系[email protected]。
版权声明:以上内容为用户推荐收藏至CareerEngine平台,其内容(含文字、图片、视频、音频等)及知识版权均属用户或用户转发自的第三方网站,如涉嫌侵权,请通知[email protected]进行信息删除。如需查看信息来源,请点击“查看原文”。如需洽谈其它事宜,请联系[email protected]。