【Python】连接常用数据库
作者:互联网
Python 连接常用数据库
Mongodb
-
安装
pymongo
包pip install pymongo
-
插入数据
from pymongo import MongoClient client = MongoClient("mongodb://localhost:27017/") # get or create database db = client["Demo"] # get or create collection col = db["customers"] # insert one record data = col.insert_one({ "name": "wilson", "sex": 1, "address": "tian he", "created": datetime.now() }) # close connection client.close()
-
查询数据
from pymongo import MongoClient client = MongoClient("mongodb://localhost:27017/") # get or create database db = client["Demo"] # get or create collection col = db["customers"] # find one data = col.find_one() print(data) # find all datas = col.find() for data in datas: print(data)
Azure SQL databases
-
安装
freetds
驱动brew install freetds
-
安装
pymssql
包pip install pymssql
-
插入数据
import pymssql conn = pymssql.connect(server='yourserver.database.windows.net', user='yourusername@yourserver', password='yourpassword', database='AdventureWorks') cursor = conn.cursor() cursor.execute("INSERT SalesLT.Product (Name, ProductNumber, StandardCost, ListPrice, SellStartDate) OUTPUT INSERTED.ProductID VALUES ('SQL Server Express', 'SQLEXPRESS', 0, 0, CURRENT_TIMESTAMP)") row = cursor.fetchone() while row: print "Inserted Product ID : " +str(row[0]) row = cursor.fetchone() conn.commit() conn.close()
-
查询数据
import pymssql conn = pymssql.connect(server='yourserver.database.windows.net', user='yourusername@yourserver', password='yourpassword', database='AdventureWorks') cursor = conn.cursor() cursor.execute('SELECT c.CustomerID, c.CompanyName,COUNT(soh.SalesOrderID) AS OrderCount FROM SalesLT.Customer AS c LEFT OUTER JOIN SalesLT.SalesOrderHeader AS soh ON c.CustomerID = soh.CustomerID GROUP BY c.CustomerID, c.CompanyName ORDER BY OrderCount DESC;') row = cursor.fetchone() while row: print str(row[0]) + " " + str(row[1]) + " " + str(row[2]) row = cursor.fetchone()
标签:database,Python,数据库,col,cursor,pymssql,连接,conn,row 来源: https://www.cnblogs.com/WilsonPan/p/14074222.html