使用MySQLdb连接MySQL数据库

使用MySQLdb连接MySQL数据库
 
不用说,先要安装MySQLdb包~

首先分析下一个简单的数据库API需要什么:
导入MySQLdb模块
建立一个到MySQL服务器的连接
执行查寻/修改操作
关闭连接

OK,下面开始,写一个查询MySQL服务器版本的程序:

# server_ver.py
#导入模块

import MySQLdb
# 建立连接,如果成功,则返回一个连接对象
conn = MySQLdb.connect(host = "localhost",
                                                    user = "testuser",
                                                    passwd = "testpass",
                                                    db = "test")
# 也可以这样:
# conn = MySQLdb.connect('localhost','root','password','dbname')
# cursor(),数据库操作都用到这个,返回一个cursor对象
cur = conn.cursor()
# 执行SQL查询语句(一般会返回一个长整数)
cur.execute("SELECT VERSION()")
# fetchone()返回一个包含第一行查询结果的元组
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我在测试时是一个长整数
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)
# 关闭连接
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)
 
当需要在函数/类中定义一个数据库查询/修改方法时,你可以这样:
 
old_name = 'ZMM'
new_name = 'ZhangMM'
cur.execute("""
                      UPDATE friend SET name = %s
                      WHERE name = %s
              """,(new_name, old_name))

文章引用自:http://www.kitebird.com/articles/pydbapi.html


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值