概述
Mysql操作
#!/usr/bin/env python
#coding=utf-8
import pprint
import pymysql
def mysql_query_create_csv(file_path,v_sql,
host='127.0.0.1', port=3306, user='root',
passwd=None, db=None, charset='utf8'
):
##sql相关配置
conn = pymysql.connect( host=host, port=port, user=user, passwd=passwd, db=db, charset=charset )
cur = conn.cursor()
cur.execute( v_sql )
indexs = cur.description
rows = cur.fetchall()
for row in rows :
pprint.pprint(row)
cur.close()
conn.close()
mssql操作
#!/usr/bin/env python
#coding=utf-8
import pymssql
import go_csv
class MSSQL:
def __init__(self,host,user,pwd,db):
self.host = host
self.user = user
self.pwd = pwd
self.db = db
def __GetConnect(self):
if not self.db:
raise(NameError,"没有设置数据库信息")
self.conn = pymssql.connect(host=self.host,user=self.user,password=self.pwd,database=self.db,charset="utf8")
cur = self.conn.cursor()
if not cur:
raise(NameError,"连接数据库失败")
else:
return cur
def ExecQuery(self,sql):
cur = self.__GetConnect()
cur.execute(sql)
resList = cur.fetchall()
#查询完毕后必须关闭连接
self.conn.close()
return resList,cur
def ExecNonQuery(self,sql):
cur = self.__GetConnect()
cur.execute(sql)
self.conn.commit()
self.conn.close()
if __name__ == "__main__" :
v_sql="select * from sys.database"
ms = MSSQL( host='127.0.0.1', user="sa", pwd="sa", db="testdb" )
rows,cur = ms.ExecQuery( v_sql )
for row in rows :
print(row)
mogodb操作
#coding=utf-8
from pymongo import MongoClient
def query_create_csv():
keys = { "_id": 1 , "name" : 1 }
client = None
try :
client = MongoClient( host='127.0.0.1', port=27017 )
db = client.mydatabase
collection = db.mycol
query = {}
item = collection.find( query, keys ).limit( 1 )
print(item.count)
for rows in item:
print( rows.values() )
except Exception as ex :
print(ex)
finally:
if client:
client.close()
if __name__ == "__main__":
query_create_csv()
Redis操作
#coding=utf-8
import redis
client = redis.Redis(host='localhost',port=6379,db=1)
print client.set('mykey','myval')
print client.get('mykey')
print client['mykey']
print client.keys()
print client.delete('mykey')
print client.set('mykey','myval2')
print client.save()
print client.flushdb()
print client.get('mykey')
最后
以上就是忧心白羊为你收集整理的python连接各种数据库数据_【python】各种数据库连接操作的全部内容,希望文章能够帮你解决python连接各种数据库数据_【python】各种数据库连接操作所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
发表评论 取消回复