您的位置:首页 > 编程语言 > Python开发

Python使用web.py读取Mysql的数据

2016-04-18 18:07 811 查看
读取mysql 的数据有两种方式

1.MySQLdb模块操作的MYSQL数据库

import MySQLdb;

import urllib2;

import os;

import re;

from urllib import urlopen;

#import urllib2.request;

conn = MySQLdb.connect(host="127.0.0.1",user="root",passwd="root",charset="utf8");

cur = conn.cursor();

cur.execute("USE test");#指定数据库

cur.execute("TRUNCATE TABLE cri");#指定数据库中的数据表

content = urllib2.urlopen(("xx.txt"));#读取在线文件或指定路径的文件

idPattern = r"\d{8}\.\d{2}";

pattern = re.compile(idPattern);

match = pattern.findall(content.read());

sql = "INSERT INTO cri (CRI) VALUES(%s)";

for i in match:

     cur.execute(sql, i);

#cur.execute("SELECT * FROM cri");

cur.close();

conn.commit();

conn.close()

2.使用web.py

 class getPltfList(object):
def __init__(self):
self.db = web.database(dbn='data_name', db = 'table_name', user = 'root', pw= ' ', host = '127.0.0.1')
self.db.printing = True#是指打印mysql语句

def ___call__(self):
return self.createPltfList()

def createPltfList(self):
self.pltfList = list(self.db.query('select name, ip from EPISODE_INSTANT_INFO order by id DESC'))

if __name__ == '__main__' :
pltfList = getPltfList()()
for pltf in pltfList:
print pltf['name'], pltf['ip']
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  web.py python mysql