Python链接数据库

MYSQL

# encoding:utf-8
import MySQLdb

conn = MySQLdb.connect(host='***.***.***.***', port=3306, user='***', passwd='***', db='****', )
cur = conn.cursor()
aa = cur.execute('select * from user_info')

print aa

# 打印表中的多少数据
info = cur.fetchmany(aa)
for ii in info:
    print ii
cur.close()
conn.commit()
conn.close()

 MongDB

# encoding:utf-8


from pymongo import MongoClient
import json
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
# client = MongoClient('***.***.***.***', 27017)

# admin 数据库有帐号,连接-认证-切换库
# uri = 'mongodb://' + user + ':' + pwd + '@' + server + ':' + port +'/'+ db_name
uri = 'mongodb://ntalker:ntalker@***.***.***.***:27017/db_name'
client = MongoClient(uri)
db_name = 'db_name'
db = client[db_name]

print db.collection_names()

collection = db['test_message']

# 访问表的一行数据˚
print collection.find_one()

# 得到所有的列
for rows in collection.find_one():
    print rows

# 访问表的数据,指定列
item = collection.find()
for rows in item:
    _id = rows["_id"]
    data = json.dumps(rows['msg'], ensure_ascii=False)
    print data
    json_to_python = json.loads(data)
    text = []
    for content in json_to_python:
        src_type = content['source_type']
        txt = content["content"]
        if src_type == u'访客' and not str(txt).startswith(u"https://") and not str(txt).startswith(u"http://"):
            text.append(content["content"])

    print text
    rows["text"] = text
    collection.save(rows)

 

posted @ 2017-08-04 18:26  zhuhc  阅读(158)  评论(0编辑  收藏  举报