第一篇:操纵MySQL数据库(1) - 基于MySQLdb库

前言

       本文讲解在Python语言中使用MySQLdb库操纵MySQL数据库的方法。

准备工作

1. 安装Python和MySQL
2. 安装MySQLdb (exe下载地址:http://sourceforge.net/projects/mysql-python/?source=typ_redirect)

总体步骤

1. 创建一个数据库;
2. 导入MySQLdb库;
3. 新建一个连接对象;
4. 基于 2 中所创建的对象新建一个游标;
5. 初始化SQL命令字符串;
6. 将 4 中创建的字符串传递进 3 中创建的游标内执行;
7. 从游标内取数并展示;
8. 提交事务;
9. 关闭游标;
10. 关闭连接对象。

       注:1为MySQL交互式执行部分,其余为Python代码部分

代码示例

 1 # -*- coding: utf-8 -*-
 2 # ================================================
 3 #  作者: 方萌
 4 #  创建时间: 20**/**/**
 5 #  版本号: 1.0
 6 #  联系方式: 1505033833@qq.com
 7 # ================================================
 8 import MySQLdb
 9 import sys
10 # 连接数据库 
11 try:
12     conn = MySQLdb.connect(host='localhost', user='root', passwd='123456', db='testDB')
13 except Exception, e:
14     print e
15     sys.exit()
16 # 获取cursor对象来进行操作
17 cursor = conn.cursor()
18 # 创建表
19 sql = "create table if not exists testTable(name varchar(128) primary key, age int(4))"
20 # 执行
21 cursor.execute(sql)
22 # 插入数据
23 sql = "insert into testTable(name, age) values ('%s', %d)" % ("方萌", 23)
24 # 执行
25 try:
26     cursor.execute(sql)
27 except Exception, e:
28     print e
29 sql = "insert into testTable(name, age) values ('%s', %d)" % ("张三", 21)
30 try:
31     cursor.execute(sql)
32 except Exception, e:
33     print e
34 # 插入多条数据
35 sql = "insert into testTable(name, age) values (%s, %s)"
36 val = (("李四", 24), ("王五", 25), ("洪六", 26))
37 try:
38     cursor.executemany(sql, val)
39 except Exception, e:
40     print e
41 # 查询出数据
42 sql = "select * from testTable"
43 cursor.execute(sql)
44 # 从游标中取出所有数据
45 alldata = cursor.fetchall()
46 # 如果有数据返回,就循环输出, alldata是由个二维的元组构成的元组。
47 if alldata:
48     for rec in alldata:
49         print rec[0], rec[1]
50 # 提交事务
51 cursor.commit()
52 
53 # 关闭游标和连接对象
54 cursor.close()
55 conn.close()

       运行结果

       

小结

       使用Python连接数据库非常简单方便。

posted @ 2017-05-20 17:05  穆晨  阅读(1073)  评论(0编辑  收藏  举报