from django.shortcuts import render_to_response
import MySQLdb
def book_list(request):
db = MySQLdb.connect(user='me', db='mydb', passwd='secret', host='localhost')
cursor = db.cursor()
cursor.execute('SELECT name FROM books ORDER BY name')
names = [row[0] for row in cursor.fetchall()]
db.close()
return render_to_response('book_list.html', {'names': names})
DATABASES = {
'default': { #默认代码如下这时候看我操作
'ENGINE': 'django.db.backends.postgresql_psycopg2', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'.
'NAME': 'postgres',#默认有一个数据库 # Or path to database file if using sqlite3.
# The following settings are not used with sqlite3:
'USER': 'postgres',#默认用户名
'PASSWORD': '911027',
'HOST': '', # Empty for localhost through domain sockets or '127.0.0.1' for localhost through TCP.
'PORT': '', #上面两项都留空 # Set to empty string for default.
}
}
下面就是验证一下是否配置成功,看我图片中的操作即可。
如果最后没出现错误则表示配置成功。要不然就会出现错误信息,常见的有下面几种。
表 5-2. 数据库配置错误信息
错误信息解决方法
You haven’t set the DATABASE_ENGINE setting yet.
不要以空字符串配置`` DATABASE_ENGINE`` 的值。 表格 5-1 列出可用的值。
INSTALLED_APPS = (
#'django.contrib.auth',
#'django.contrib.contenttypes',
#'django.contrib.sessions',
#'django.contrib.sites',
#'django.contrib.messages',
#'django.contrib.staticfiles',
'books',
# Uncomment the next line to enable the admin:
# 'django.contrib.admin',
# Uncomment the next line to enable admin documentation:
# 'django.contrib.admindocs',
)
另外还要将下面MIDDLEWARE_CLASSES的代码修改为如此: