Method One:
1, need to install pymssql
pip install pymssql
2. Connection code:
import pymssqlconn=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()
The following is the Django action method two (Django operation):
1, install the necessary components:
pip install django-sqlserver django-pytds pyodbc django-pyodbc pypiwin32
2, modify the 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‘, }, }}
Method Three (Django):
1. You need to install SQL Server Management Studio or the manually install Microsoft Data Access components (MDAC) program.
2. Install Django-mssql and Pywin32:
pip install django-mssql
3, modify the 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为‘SQLCLI10‘时若有问题,可改成‘SQLOLEDB‘ ,反之亦然。 ‘provider‘: ‘SQLOLEDB‘, # Have also tried ‘SQLCLI11‘ and ‘SQLOLEDB‘ ‘extra_params‘: ‘DataTypeCompatibility=80‘ }, }}
Method Four (Django):
1. Installation of Django-pyodbc-azure and PYODBC
pip install django-pyodbc-azure pyodbc
2, modify the 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 poolingDATABASE_CONNECTION_POOLING = False
Python connects to the SQL Server database