在Django中可以在视图函数中使用python来实现,不过更简单的方法是在settings.py中设置,这样可以减少冗余代码,实现数据层剥离。
相信大多数人使用的是Mysql,这里不介绍Mysql怎么装以及配置了,打开settings.py设置如下:
DATABASES = {
'default': {
#'ENGINE': 'django.db.backends.', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'.
'ENGINE':'django.db.backends.mysql',
'NAME': 'test', # Or path to database file if using sqlite3.
'USER': 'root', # Not used with sqlite3.
'PASSWORD': 'wang', # Not used with sqlite3.
'HOST': '', # Set to empty string for localhost. Not used with sqlite3.
'PORT': '', # Set to empty string for default. Not used with sqlite3.
}
}
ENGINE指明用哪一个数据库适配器,很多材料中都是用mysql,而在我的机器上,用django.db.backends.mysql才生效。
NAME指明所用的数据库名称
USER指明登录数据库的用户名
PASSWORD指明登录密码
好了,测试一下,在项目目录下输入python manage.py shell,如果没有错误信息,那么就说明是设置正确的。
在shell模式下输入from django.db import connection.
cursor = connection.cursor()
是不是感觉很熟悉了,接下来的数据库操作相信大家就都会了。确实很方便。
使用其他数据库,或想知道更多内容的朋友请参见:
http://djangobook.py3k.cn/2.0/chapter05/