您好,登錄后才能下訂單哦!
我是使用pymssql完成的sqlserver,首先下載符合版本的pymssql的whl,然后安裝,在pycharm的default setting->project Interpreter中確定項目的Interpreter有pymssql,然后就開始了~
` # -*- coding:utf-8 -*- import hashlib import hmac import json import pymssql from requests import Response from rest_framework import status, generics from rest_framework.decorators import api_view from rest_framework.views import APIView from django.http import HttpResponse, HttpRequest @api_view(['GET', 'POST']) def userlogin(req,format=None): ms = MSSQL(host="你的IP地址", user="你的數據庫賬號", pwd="你的數據庫密碼", db="你的數據庫名") if req.method == 'GET': username = req.GET['username'] password = req.GET['password'] elif req.method == 'POST': username= req.POST['username'] password = req.POST['password'] newsql = "select * from System_Users where Mobile = '"+username+"'" print(newsql) reslist = ms.ExecQuery(newsql.encode('utf-8')) # //驗證password加密后==LoginPwd print(password) print(reslist[0].get("LoginKey")) if Encrypt(password,reslist[0].get("LoginKey"))==reslist[0].get("LoginKey"): reslist =json_success(reslist) else: reslist =json_error(reslist) # meizis = System_Users.objects.all() # serializer = MeiziSerializer(reslist, many=True) # return Response(serializer.data) return HttpResponse(json.dumps(reslist, default=lambda obj: obj.__dict__), content_type='application/json') # return reslist def Encrypt(password="",salt = ""): clearBytes=[] hasheByte=[] # # encoding = unicode # clearBytes= bytes(salt.lower().strip()+password.strip(),encoding='Unicode') # salt = crypt.mksalt(crypt.METHOD_SHA512) # 然后再進行數據加密: # hasheByte = crypt.crypt("helloworld", salt) # hasheByte =crypt.crypt(clearBytes, salt) # password = hmac.new(key=clearBytes, msg=password) # 待加密信息 str =salt.lower().strip()+password.strip() # 創建md5對象 hl = hashlib.md5() # Tips # 此處必須聲明encode # 若寫法為hl.update(str) 報錯為: Unicode-objects must be encoded before hashing print('MD5加密前為 :' + str) hl.update(str.encode(encoding='utf-16')) print('MD5加密后為 :' + hl.hexdigest()) hl.update(str.encode(encoding='UTF-8')) print('MD5加密后為 :' + hl.hexdigest()) hl.update(str.encode(encoding='GBK')) print('MD5加密后為 :' + hl.hexdigest()) hl.update(str.encode(encoding='GB2312')) print('MD5加密后為 :' + hl.hexdigest()) print(password) return password def json_success(data, code=200, foreign_penetrate=False, **kwargs): data = { "status": code, "msg": "成功", "data": data, } print(data) return data def json_error(error_string="失敗", code=500, **kwargs): data = { "status": code, "msg": error_string, "data": {} } data.update(kwargs) return data 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="GBK") 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() col_names = [desc[0] for desc in cur.description] result = [] for row in resList: objDict = {} # 把每一行的數據遍歷出來放到Dict中 for index, value in enumerate(row): index, col_names[index], value objDict[col_names[index]] = value result.append(objDict) # 查詢完畢后必須關閉連接 self.conn.close() return result def ExecNonQuery(self, sql): cur = self.__GetConnect() cur.execute(sql) self.conn.commit() self.conn.close()
然后設置好url就ok了,這是在Django框架下,fask框架下鏈接數據庫模塊依然可以使用
補充知識:使用pycharm連接數據庫---Sqlalchemy
初識sqlalchemy
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column,String,INTEGER
#1.創建引擎
eng = create_engine("mysql+pymysql://root:admin@localhost/homework?charset=utf8")
print(eng)
#2.創建基類
Base = declarative_base()
#3.創建類(模型)
class Student(Base):
__tablename__="student1"#指定表格名稱
id = Column(INTEGER,primary_key=True,autoincrement=True)
name = Column(String(32),nullable=False)#非空約束
email = Column(String(32),unique=True)#唯一約束
#4.創建表格
Base.metadata.create_all(eng)
#5刪除表格
Base.metadata.drop_all(eng)
創建出來的student1表
使用Sqlalchemy四部曲:
1、使用create_engine()#連接數據庫
2、Base = declarative_base()# 生成orm基類,用于創建classes
3、Base.metadata.create_all(engine) #關聯engine使用metadata創建數據庫表
4、使用 session = Session(engine) #創建一個會話,便于后面對數據庫進行實際操作
from sqlalchemy import create_engine from sqlalchemy.ext.declarative import declarative_base from sqlalchemy import Column,String,INTEGER from sqlalchemy.orm import sessionmaker #1.創建引擎 eng = create_engine("mysql+pymysql://root:admin@localhost/homework?charset=utf8") #2.創建基類 Base = declarative_base() #3.創建類(模型) class Student(Base): __tablename__ = "student2" id = Column(INTEGER,primary_key=True,autoincrement=True) name = Column(String(32), nullable=False) # 非空約束 email = Column(String(32), unique=True) # 唯一約束 #4.創建表格 Base.metadata.create_all(eng) #5.創建session Session = sessionmaker(bind=eng) session = Session()#創建session對象,相當于pymysql中的conn #增加記錄 # student = Student(name='劉備',email='120@qq.com')#創建student的對象 # session.add(student)#添加記錄 # #批量增加 # session.add_all( # [ # Student(name='張飛',email='110@qq.com'), # Student(name='悟空',email='111@qq.com'), # Student(name='宮本',email='112@qq.com'), # Student(name='趙云',email='113@qq.com'), # ] # ) #查詢操作 #first方法查詢出第一條記錄 # ret = session.query(Student).first() # print(ret.id,ret.name,ret.email) # #get方法查詢指定記錄 # student = session.query(Student).get(ident=2)#使用唯一標識ident不寫也行查詢第幾條記錄 # print(student.id,student.name,student.email) # # student = session.query(Student).filter(Student.id>2)#filter過濾相當于條件 # for stu in student:#這里的student是個對象,所以需要把他遍歷出來顯示查詢出來的數據 # print(stu.id,stu.name,stu.email) # #刪除操作 # # student = session.query(Student).filter(Student.id<2).delete() # # #方式一此方法可刪除多個主要是因為filter,他是條件嗎滿足他的都可以被刪除 # student1 = session.query(Student).get(2) # session.delete(student1)#方式二 # #修改操作 #單條修改 # student3 =session.query(Student).first() # student3.name='百度' # student3.email='www.baidu.com' #指定條件修改 student4 =session.query(Student).filter(Student.id ==3).update({Student.name:'王炸',Student.email:'666@qq.com'}) session.commit()#提交事務 session.close()
以上這篇python 鏈接sqlserver 寫接口實例就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持億速云。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。