首页 > 代码库 > Python链接数据库

Python链接数据库

MYSQL

# encoding:utf-8import MySQLdbconn = 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 iicur.close()conn.commit()conn.close()

 MongDB

# encoding:utf-8from pymongo import MongoClientimport jsonimport sysreload(sys)sys.setdefaultencoding(utf-8)# client = MongoClient(‘***.***.***.***‘, 27017)# admin 数据库有帐号,连接-认证-切换库# uri = ‘mongodb://‘ + user + ‘:‘ + pwd + ‘@‘ + server + ‘:‘ + port +‘/‘+ db_nameuri = mongodb://ntalker:ntalker@***.***.***.***:27017/db_nameclient = MongoClient(uri)db_name = ‘db_namedb = 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)

 

Python链接数据库