方法一:
1、需要安装pymssql
pip install pymssql
2、使用方法:
import pymssql
conn=pymssql.connect(host=‘127.0.0.1‘,user=‘user‘,password=‘password‘,database=‘MyDB‘)
cur=conn.cursor()
cur.execute(‘select * from table1‘)
#如果是插入、删除、更新语句切记要写提交命令con.commit()
print (cur.fetchall())
cur.close()
conn.close()
方法二:
1、安装必要的组件:
pip install django-sqlserver django-pytds pyodbc django-pyodbc pypiwin32
2、修改settings.py的DATABASES:
DATABASES = {
# ‘default‘: {
# ‘ENGINE‘: ‘django.db.backends.sqlite3‘,
# ‘NAME‘: os.path.join(BASE_DIR, ‘db.sqlite3‘),
# }
‘default‘: {
‘ENGINE‘: ‘sqlserver‘,
‘NAME‘: ‘MyDB‘,
‘HOST‘: ‘127.0.0.1‘,
‘PORT‘: ‘1433‘,
‘USER‘: ‘user‘,
‘PASSWORD‘: ‘password,
‘OPTIONS‘: {
‘DRIVER‘: ‘SQL Server Native Client 10.0‘,
},
}
}
方法三:
1、需要安装 SQL Server Management Studio 或者 manually install Microsoft Data Access Components (MDAC)程序。
2、安装django-mssql和pywin32:
pip install django-mssql
3、修改settings.py的DATABASES:
DATABASES = {
# ‘default‘: {
# ‘ENGINE‘: ‘django.db.backends.sqlite3‘,
# ‘NAME‘: os.path.join(BASE_DIR, ‘db.sqlite3‘),
# }
‘default‘: {
‘NAME‘: ‘MyDB‘,
‘ENGINE‘: ‘sqlserver_ado‘,
‘HOST‘: ‘127.0.0.1‘,
‘USER‘: ‘user‘,
‘PASSWORD‘: ‘password‘,
‘OPTIONS‘: {
‘provider‘: ‘SQLOLEDB‘, # Have also tried ‘SQLCLI11‘ and ‘SQLOLEDB‘
‘extra_params‘: ‘DataTypeCompatibility=80‘
},
}
}
provider为‘SQLCLI10‘时若有问题,可改成‘SQLOLEDB‘ ,反之亦然。
方法四:
1、安装django-pyodbc-azure和pyodbc
pip install django-pyodbc-azure pyodbc
2、修改settings.py的DATABASES:
DATABASES = {
‘default‘: {
‘ENGINE‘: ‘sql_server.pyodbc‘,
‘NAME‘: ‘MyDB‘,
‘USER‘: ‘user‘,
‘PASSWORD‘: ‘password‘,
‘HOST‘: ‘127.0.0.1‘,
‘PORT‘: ‘‘,
‘OPTIONS‘: {
‘driver‘:‘SQL Server Native Client 11.0‘,
‘MARS_Connection‘: True,
},
},
}
# set this to False if you want to turn off pyodbc‘s connection pooling
DATABASE_CONNECTION_POOLING = False