使用MySQLdb连接MySQL数据库
不用说,先要安装MySQLdb包~
首先分析下一个简单的数据库API需要什么:
导入MySQLdb模块
建立一个到MySQL服务器的连接
执行查寻/修改操作
关闭连接
OK,下面开始,写一个查询MySQL服务器版本的程序:
# server_ver.py
#导入模块
import MySQLdb
#导入模块
import MySQLdb
# 建立连接,如果成功,则返回一个连接对象
conn = MySQLdb.connect(host = "localhost",
user = "testuser",
passwd = "testpass",
db = "test")
# 也可以这样:
# conn = MySQLdb.connect('localhost','root','password','dbname')
conn = MySQLdb.connect(host = "localhost",
# 也可以这样:
# conn = MySQLdb.connect('localhost','root','password','dbname')
# cursor(),数据库操作都用到这个,返回一个cursor对象
cur = conn.cursor()
cur = conn.cursor()
# 执行SQL查询语句(一般会返回一个长整数)
cur.execute("SELECT VERSION()")
cur.execute("SELECT VERSION()")
# fetchone()返回一个包含第一行查询结果的元组
row = cur.fetchone()
print "server version:", row[0]
# 关闭连接
cur.close()
conn.close()
# 连接关闭后,将不能对数据库进行操作
row = cur.fetchone()
print "server version:", row[0]
# 关闭连接
cur.close()
conn.close()
# 连接关闭后,将不能对数据库进行操作
保存后,我们运行这个程序:
c:\edit>python server_ver.py
server version: 4.0.24-nt
下面进行稍复杂的操作--建表/写入数据
....
cur = conn.cursor()
# 表存在时,删除
cur.execute("DROP TABLE IF EXISTS friend")
cur.execute("""
CREATE TABLE friend
(
name CHAR(20),
category CHAR(40)
)
""")
# 写表,(name, category)也可以省略
cur.execute("""
INSERT INTO friend (name, category)
VALUES
('andelf', 'myself'),
('ZCX', 'Sister'),
('Feather', 'myname'),
('ZMM', 'nothingtosay')
""")
# 运行查询语句
cur.execute("SELECT name, category FROM friend")
# cur.rowcount我在测试时是一个长整数
cur = conn.cursor()
# 表存在时,删除
cur.execute("DROP TABLE IF EXISTS friend")
cur.execute("""
# 写表,(name, category)也可以省略
cur.execute("""
# 运行查询语句
cur.execute("SELECT name, category FROM friend")
# cur.rowcount我在测试时是一个长整数
print "%d rows were updated" % int(cur.rowcount)
# 打印出查询内容
while True:
row = cur.fetchone()
if row == None:
break
print "%s, %s" % row
print "%d rows were returned" % int(cur.rowcount)
# 打印出查询内容
while True:
print "%d rows were returned" % int(cur.rowcount)
# 关闭连接
cur.close()
conn.close()
cur.close()
conn.close()
注:查询返回的是一个元组,当使用语句
cur = conn.cursor(MySQLdb.cursors.DictCursor)时,查询将返回一个包含字典的元组,字典以name,category为索引关键字.
# 更新内容
cur.execute("""
UPDATE friend SET name = 'ZhangMM'
WHERE name = 'ZMM'
""")
print "%d rows were updated" % int(cur.rowcount)
cur.execute("""
print "%d rows were updated" % int(cur.rowcount)
当需要在函数/类中定义一个数据库查询/修改方法时,你可以这样:
old_name = 'ZMM'
new_name = 'ZhangMM'
cur.execute("""
UPDATE friend SET name = %s
WHERE name = %s
""",(new_name, old_name))
new_name = 'ZhangMM'
cur.execute("""
文章引用自:http://www.kitebird.com/articles/pydbapi.html