# -*- coding: UTF-8 -*-
import MySQLdb
import time
#警告信息try except是无法捕捉的
from warnings import filterwarnings
filterwarnings("error’, category = MySQLdb.Warning)
cursor = conn = delete_id = update_id = 0
try:
conn = MySQLdb.connect(host=’10.200.10.203′, user=’test’, passwd=’test’, db=’test’, port=3306,charset=’utf8′)
cursor = conn.cursor()
#创建表
create_tabl_sql = “””CREATE TABLE IF NOT EXISTS `test` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(200) NOT NULL,
`create_time` datetime NOT NULL,
`content` text NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8″””
#cursor.execute(create_tabl_sql)
except MySQLdb.Warning, w:
print “警告信息 %s” % str(w)
except MySQLdb.Error, e:
print “错误信息 %d %s” % (e.args[0], e.args[1])
# 查询数据
select_data_sql = “select * from test”
print “执行语句: %s” % select_data_sql
try:
cursor.execute(select_data_sql)
result = cursor.fetchone() #读取一行数据
print "获取记录数:%d’ % cursor.rowcount #返回总记录数
print u’编号:%d,姓名:%s,时间:%s,内容:%s’ % (result[0], result[1], result[2], result[3])
#读取指定行内容
result_many = cursor.fetchmany(2) #读取2行数据
print "获取记录数:%d’ % cursor.rowcount #返回总记录数
print result_many
results = cursor.fetchall() #读取所有数据
print "获取记录数:%d’ % cursor.rowcount #返回总记录数
for row in results:
print "编号:%d’ % (row[0])
print u’姓名:%s’ % (row[1])
print u’内容:%s’ % (row[3])
except :
# 异常回滚
print "查询数据失败’
cursor.close()
conn.close()