Centos下安装sudo yum install Mysql-python可以参考Http://www.mikusa.com/Python-mysql-docs/index.html 获取更多信息Mysql-python 为Python
Centos下安装
可以参考Http://www.mikusa.com/Python-mysql-docs/index.html 获取更多信息
Mysql-python 为Python提供MySQL驱动程序,主要包括两个部件,_mysql和MySQLdb
连接数据库
In [56]: import MySQLdb
In [57]: db=MySQLdb.connect(host='127.0.0.1',user='xxx',passwd='xxx',db='xxx')
2.创建游标
为了能够在多处使用同一个连接,可以创建一个游标对象
In [60]: cur=db.cursor()
3.执行MySQL查询操作
创建数据库表
In [62]: cur.execute("CREATE TABLE song (id INT UNSIGNED PRIMARY KEY AUTO_INCREMENT,title TEXT NOT NULL)")
In [67]: songs=('Purple Haze','All Along the Watch Tower','Foxy Lady')
In [68]: for song in songs:
....: cur.execute("INSERT INTO song(title) VALUES (%s)",song)
....: print "Auto Increment ID: %s" %cur.lastrowid
....:
In [5]: cur.execute("SELECT * FROM song WHERE id = %s or id = %s",(1,2))
In [7]: numrows=cur.execute("SELECT * FROM song")
4.获取查询结果
当执行了任何查询操作后,可以用fetchall()或者fetchone()获取
#/usr/bin/python
import MySQLdb
db=MySQLdb.connect(host='127.0.0.1',user='xxx',passwd='xxx',db='xxx')
cur=db.cursor()
cur.execute("SELECT * FROM account")
rows=cur.fetchall()
for row in rows:
for col in row:
print "%s," %col
print "\n"
In [70]: cur.execute("SELECT * FROM song WHERE id=1")
In [71]: print "ID: %s -- Title: %s" %cur.fetchone()
5.异常处理
import MySQLdb
db=MySQLdb.connect(host='127.0.0.1',user='jialebi',passwd='jialebi123',db='dream_Android_game_center')
cur=db.cursor()
try:
cur.execute("SELECT * FROM account")
rows=cur.fetchall()
except MySQLdb.Error,e:
try:
print "MySQL Error [%d] : %s" % (e.args[0],e.args[1])
except IndexError:
print "MySQL Error: %s" % str(e)
for row in rows:
for col in row:
print "%s," %col
print "\n"
6.清理连接
n [74]: cur.close()
In [75]: db.close()
--结束END--
本文标题: Python学习之MySQLdb模块
本文链接: https://lsjlt.com/news/184800.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
2024-10-23
2024-10-22
2024-10-22
2024-10-22
2024-10-22
2024-10-22
2024-10-22
2024-10-22
2024-10-22
2024-10-22
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0