我是使用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")
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") #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 写接口实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。
更新动态
- 凤飞飞《我们的主题曲》飞跃制作[正版原抓WAV+CUE]
- 刘嘉亮《亮情歌2》[WAV+CUE][1G]
- 红馆40·谭咏麟《歌者恋歌浓情30年演唱会》3CD[低速原抓WAV+CUE][1.8G]
- 刘纬武《睡眠宝宝竖琴童谣 吉卜力工作室 白噪音安抚》[320K/MP3][193.25MB]
- 【轻音乐】曼托凡尼乐团《精选辑》2CD.1998[FLAC+CUE整轨]
- 邝美云《心中有爱》1989年香港DMIJP版1MTO东芝首版[WAV+CUE]
- 群星《情叹-发烧女声DSD》天籁女声发烧碟[WAV+CUE]
- 刘纬武《睡眠宝宝竖琴童谣 吉卜力工作室 白噪音安抚》[FLAC/分轨][748.03MB]
- 理想混蛋《Origin Sessions》[320K/MP3][37.47MB]
- 公馆青少年《我其实一点都不酷》[320K/MP3][78.78MB]
- 群星《情叹-发烧男声DSD》最值得珍藏的完美男声[WAV+CUE]
- 群星《国韵飘香·贵妃醉酒HQCD黑胶王》2CD[WAV]
- 卫兰《DAUGHTER》【低速原抓WAV+CUE】
- 公馆青少年《我其实一点都不酷》[FLAC/分轨][398.22MB]
- ZWEI《迟暮的花 (Explicit)》[320K/MP3][57.16MB]