Python MySQLdb模块
2014-01-10 11:35
309 查看
mysql是一个优秀的开源数据库,它现在的应用非常的广泛,因此很有必要简单的介绍一下用python操作mysql数据库的方法。python操作数 据库需要安装一个第三方的模块,在http://mysql-python.sourceforge.net/有下载和文档。
#-*- encoding: gb2312 -*-
import os, sys, string
import MySQLdb
# 连接数据库
try:
conn = MySQLdb.connect(host='localhost',user='root',passwd='xxxx',db='test1')
except Exception, e:
print e
sys.exit()
# 获取cursor对象来进行操作
cursor = conn.cursor()
# 创建表
sql = "create table if not exists test1(name varchar(128) primary key, age int(4))"
cursor.execute(sql)
# 插入数据
sql = "insert into test1(name, age) values ('%s', %d)" % ("zhaowei", 23)
try:
cursor.execute(sql)
except Exception, e:
print e
sql = "insert into test1(name, age) values ('%s', %d)" % ("张三", 21)
try:
cursor.execute(sql)
except Exception, e:
print e
# 插入多条
sql = "insert into test1(name, age) values (%s, %s)"
val = (("李四", 24), ("王五", 25), ("洪六", 26))
try:
cursor.executemany(sql, val)
except Exception, e:
print e
#查询出数据
sql = "select * from test1"
cursor.execute(sql)
alldata = cursor.fetchall()
# 如果有数据返回,就循环输出, alldata是有个二维的列表
if alldata:
for rec in alldata:
print rec[0], rec[1]
cursor.close()
conn.close()
#-*- encoding: gb2312 -*-
import os, sys, string
import MySQLdb
# 连接数据库
try:
conn = MySQLdb.connect(host='localhost',user='root',passwd='xxxx',db='test1')
except Exception, e:
print e
sys.exit()
# 获取cursor对象来进行操作
cursor = conn.cursor()
# 创建表
sql = "create table if not exists test1(name varchar(128) primary key, age int(4))"
cursor.execute(sql)
# 插入数据
sql = "insert into test1(name, age) values ('%s', %d)" % ("zhaowei", 23)
try:
cursor.execute(sql)
except Exception, e:
print e
sql = "insert into test1(name, age) values ('%s', %d)" % ("张三", 21)
try:
cursor.execute(sql)
except Exception, e:
print e
# 插入多条
sql = "insert into test1(name, age) values (%s, %s)"
val = (("李四", 24), ("王五", 25), ("洪六", 26))
try:
cursor.executemany(sql, val)
except Exception, e:
print e
#查询出数据
sql = "select * from test1"
cursor.execute(sql)
alldata = cursor.fetchall()
# 如果有数据返回,就循环输出, alldata是有个二维的列表
if alldata:
for rec in alldata:
print rec[0], rec[1]
cursor.close()
conn.close()
相关文章推荐
- python 安装MySQLdb模块
- Python 导入模块import MySQLdb 出现:No module named MySQLdb
- Python MySQLdb模块连接操作mysql数据库实例
- Python 的 MySQLdb 模块插入数据没有成功与 autocommit(自动提交)的关系
- Python的MySQLdb模块安装
- Linux下安装MySQLdb模块(Python)
- python模块MySQLdb安装失败解决方法
- easy_install安装python的MySQLdb模块
- Python安装MySQLdb模块(Linux)
- 在Win7中 安装Python的MySQLdb模块 出现问题的解决方法
- python中MySQLdb模块的用法
- Python学习之MySQLdb模块
- 基础入门_Python-模块和包.运维开发中MySQLdb CRUD操作的最佳实践?
- python安装MySQLDb模块
- Python的MySQLdb模块安装(转:一个人的旅行)
- Python的MySQLdb模块安装,连接,操作,增删改
- python mysql 简单总结(MySQLdb模块 需另外下载)
- python模块整理18-MySQLdb
- Python MySQLdb模块的安装与使用