python連接SQL Server數據庫
阿新 • • 發佈:2018-01-31
sql ase ons cursor ide ant all win azure 方法一:
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()
以下為Django中操作
方法二(Django操作):
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‘, }, } }
方法三(Django):
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為‘SQLCLI10‘時若有問題,可改成‘SQLOLEDB‘ ,反之亦然。 ‘provider‘: ‘SQLOLEDB‘, # Have also tried ‘SQLCLI11‘ and ‘SQLOLEDB‘ ‘extra_params‘: ‘DataTypeCompatibility=80‘ }, } }
方法四(Django):
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
python連接SQL Server數據庫