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

时间:2022-02-18 01:14:11

前言

本文讲解在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代码部分。

代码示例

 # -*- coding: utf-8 -*-
# ================================================
# 作者: 方萌
# 创建时间: 20**/**/**
# 版本号: 1.0
# 联系方式: 1505033833@qq.com
# ================================================
import MySQLdb
import sys
# 连接数据库 
try:
conn = MySQLdb.connect(host='localhost', user='root', passwd='', db='testDB')
except Exception, e:
print e
sys.exit()
# 获取cursor对象来进行操作
cursor = conn.cursor()
# 创建表
sql = "create table if not exists testTable(name varchar(128) primary key, age int(4))"
# 执行
cursor.execute(sql)
# 插入数据
sql = "insert into testTable(name, age) values ('%s', %d)" % ("方萌", 23)
# 执行
try:
cursor.execute(sql)
except Exception, e:
print e
sql = "insert into testTable(name, age) values ('%s', %d)" % ("张三", 21)
try:
cursor.execute(sql)
except Exception, e:
print e
# 插入多条数据
sql = "insert into testTable(name, age) values (%s, %s)"
val = (("李四", 24), ("王五", 25), ("洪六", 26))
try:
cursor.executemany(sql, val)
except Exception, e:
print e
# 查询出数据
sql = "select * from testTable"
cursor.execute(sql)
# 从游标中取出所有数据
alldata = cursor.fetchall()
# 如果有数据返回,就循环输出, alldata是由个二维的元组构成的元组。
if alldata:
for rec in alldata:
print rec[0], rec[1]
# 提交事务
cursor.commit() # 关闭游标和连接对象
cursor.close()
conn.close()

运行结果

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

小结

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