Python实例讲解 -- 操作数据库 附mysqldb win32 py2.7下载
2013-08-27 10:04
806 查看
mysql是一个优秀的开源数据库,它现在的应用非常的广泛,因此很有必要简单的介绍一下用python操作mysql数据库的方法。python操作数 据库需要安装一个第三方的模块,在http://mysql-python.sourceforge.net/有下载和文档。
Python代码
# -*- coding: utf-8 -*-
import os, sys, string
import MySQLdb
# 连接数据库
try:
conn = MySQLdb.connect(host='localhost',user='root',passwd='root',db='test')
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代码
# -*- coding: utf-8 -*-
import os, sys, string
import MySQLdb
# 连接数据库
try:
conn = MySQLdb.connect(host='localhost',user='root',passwd='root',db='test')
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()
相关文章推荐
- Python2.7操作Mysql数据库及乱码解决方案(附mysqldb win32 py2.7下载)
- Python原始字符串操作符和Unicode操作符操作实例讲解源码
- 【python系列】mysqldb模块操作数据库
- python MySQLdb用法,python中cursor操作数据库(转)
- Python MYSQLdb操作数据库
- python2.7 串口操作方式 编译 .py为windows可运行exe文件
- Python3之文件读写操作的实例讲解
- [Python]MySQLdb for Python使用指南/Python的数据库操作
- python列表操作实例源码讲解(创建、使用、更新、删除)
- python 用mysqldb方式操作数据库
- python操作word之pywin32的安装
- python利用MySQLdb模块进行数据库的连接实现增查操作
- [Python]MySQLdb for Python使用指南/Python的数据库操作
- python 用mysqldb方式操作数据库
- MySQLdb for Python使用指南/Python的数据库操作
- Python之路【第八篇】:堡垒机实例以及数据库操作
- (转)[Python]MySQLdb for Python使用指南/Python的数据库操作【http://www.cnblogs.com/czh-liyu/archive/2008/04/13/1151758.html】
- python字符串内建函数操作实例源码讲解
- [Python]MySQLdb for Python使用指南/Python的数据库操作
- Python操作MySQL实例讲解