作者:200355人 | 来源:互联网 | 2023-07-10 15:13
篇首语:本文由编程笔记#小编为大家整理,主要介绍了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:[email protected]***.***.***.***: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)