每天一个python小程序 2使用python.MySQLdb执行数据库操作
2015-03-14 10:03
966 查看
第 0002 题:将 0001 题生成的 200 个激活码(或者优惠券)保存到 MySQL 关系型数据库中。
#coding=utf-8
import os,MySQLdb,re
path = os.path.split(os.path.realpath(__file__))[0]+"/"
f = open(path+"res.txt","r")
A = f.read()
conn=MySQLdb.connect("127.0.0.1","root","root","z002")
conn.autocommit(1)
cursor = conn.cursor()
arr = re.split("\s+",A)
cursor.execute("DROP TABLE IF EXISTS CODE")
sql = """CREATE TABLE CODE (
no INT primary key,
content text
)"""
cursor.execute(sql)
for i in range(len(arr)):
if i:
sql = """INSERT INTO `code` SET `no`=%s,`content`='%s'"""%(i-1,arr[i-1])
print sql
cursor.execute(sql)
在insert时,总是发现插入失败。但是却没有提示什么异常。解决方法有三
1、在sql语句后加一个COMMIT命令
2、给数据库连接conn预定一个commit
3、在释放数据库连接之前commit
#coding=utf-8
import os,MySQLdb,re
path = os.path.split(os.path.realpath(__file__))[0]+"/"
f = open(path+"res.txt","r")
A = f.read()
conn=MySQLdb.connect("127.0.0.1","root","root","z002")
conn.autocommit(1)
cursor = conn.cursor()
arr = re.split("\s+",A)
cursor.execute("DROP TABLE IF EXISTS CODE")
sql = """CREATE TABLE CODE (
no INT primary key,
content text
)"""
cursor.execute(sql)
for i in range(len(arr)):
if i:
sql = """INSERT INTO `code` SET `no`=%s,`content`='%s'"""%(i-1,arr[i-1])
print sql
cursor.execute(sql)
在insert时,总是发现插入失败。但是却没有提示什么异常。解决方法有三
1、在sql语句后加一个COMMIT命令
cursor.execute('insert into user (id, name) values (1, 'luchanghong);COMMIT;')
2、给数据库连接conn预定一个commit
conn = MySQLdb.connect(host = 'localhost', user = 'root', passwd = 'root', db = 'test') conn.autocommit(1)
3、在释放数据库连接之前commit
conn = MySQLdb.connect() cursor.execute('insert into ...') cursor.close() conn.commit() conn.close()
相关文章推荐
- [Python]MySQLdb for Python使用指南/Python的数据库操作
- [Python]MySQLdb for Python使用指南/Python的数据库操作
- Python 练习册,每天一个小程序----------001使用 Python 如何生成多位随机数
- MySQLdb for Python使用指南/Python的数据库操作
- python使用MySQLdb操作数据库
- MySQLdb for Python使用指南/Python的数据库操作
- 【转】MySQLdb for Python使用指南/Python的数据库操作
- [Python]MySQLdb for Python使用指南/Python的数据库操作
- MySQLdb for Python使用指南/Python的数据库操作
- [Python]MySQLdb for Python使用指南/Python的数据库操作
- 每天一个python小程序 3向Redis数据库中插入数据
- MySQLdb for Python使用指南/Python的数据库操作
- MySQLdb for Python使用指南/Python的数据库操作
- [Python]MySQLdb for Python使用指南/Python的数据库操作
- [Python]MySQLdb for Python使用指南/Python的数据库操作
- MySQLdb for Python使用指南/Python的数据库操作
- (转)[Python]MySQLdb for Python使用指南/Python的数据库操作【http://www.cnblogs.com/czh-liyu/archive/2008/04/13/1151758.html】
- MySQLdb for Python使用指南/Python的数据库操作
- linux下使用cron每天定时执行java程序
- python cgi ajax - 使用CGIHTTPServer实现一个ajax程序