django里能用pymysql吗
时间: 2023-09-13 12:09:26 浏览: 147
可以,在Django的settings.py中设置DATABASES选项,将ENGINE项设置为'django.db.backends.mysql',将NAME、USER、PASSWORD、HOST、PORT等项设置为连接MySQL数据库所需的信息。然后在项目中可以引用pymysql库进行操作。具体实现可以参考以下代码:
```python
# settings.py
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'mydatabase',
'USER': 'mydatabaseuser',
'PASSWORD': 'mypassword',
'HOST': 'localhost',
'PORT': '3306',
'OPTIONS': {
'charset': 'utf8mb4',
'use_unicode': True,
'init_command': "SET sql_mode='STRICT_TRANS_TABLES'"
},
}
}
# views.py
import pymysql
def my_view(request):
conn = pymysql.connect(
host='localhost',
user='mydatabaseuser',
password='mypassword',
db='mydatabase',
charset='utf8mb4',
cursorclass=pymysql.cursors.DictCursor
)
with conn.cursor() as cursor:
sql = "SELECT * FROM mytable WHERE id=%s"
cursor.execute(sql, (request.GET.get('id'),))
result = cursor.fetchone()
conn.close()
return HttpResponse(result)
```
阅读全文