python函数用法查询-Python-MySQL查询函数使用示例

# -*- 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()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值