Python Django连接数据库
一、安装数据库
# yum -y install mysql mysql-devel mysql-server
二、查看是否安装了python数据库组件
# rpm -qa | grep MySQL-python
MySQL-python-1.2.3-0.3.c1.1.el6.x86_64
三、创建数据库
# mysql -uroot -p
mysql> create database csvt character set utf8;
四、创建工程,应用
# django-admin.py startproject csvt03
# cd csvt03
# django-admin.py startapp blog
# vim settings.py (添加应用,修改数据库类型连接用户以及密码)
...
DATABASES = {
‘default‘: {
‘ENGINE‘: ‘django.db.backends.mysql‘,
‘NAME‘: ‘csvt‘,
‘USER‘: ‘root‘,
‘PASSWORD‘: ‘123456‘,
‘HOST‘: ‘‘,
‘PORT‘: ‘‘,
}
}
............
INSTALLED_APPS = (
‘django.contrib.auth‘,
‘django.contrib.contenttypes‘,
‘django.contrib.sessions‘,
‘django.contrib.sites‘,
‘django.contrib.messages‘,
‘django.contrib.staticfiles‘,
‘blog‘,
)
...
五、创建表
# cat blog/models.py
from django.db import models
class Employee(models.Model):
name = models.CharField(max_length=20)
//(会在数据库csvt employee表中添加一个name字段)
六、同步数据库,将数据写入数据库
# python manage.py syncdb
Creating tables ...
Creating table auth_permission
Creating table auth_group_permissions
Creating table auth_group
Creating table auth_user_user_permissions
Creating table auth_user_groups
Creating table auth_user
Creating table auth_message
Creating table django_content_type
Creating table django_session
Creating table django_site
Creating table blog_employee
You just installed Django‘s auth system, which means you don‘t have any superusers defined.
Would you like to create one now? (yes/no): yes
Installing custom SQL ...
Installing indexes ...
No fixtures found.
七、查看数据库
mysql> use csvt;
Database changed
mysql> show tables;
+----------------------------+
| Tables_in_csvt |
+----------------------------+
| auth_group |
| auth_group_permissions |
| auth_message |
| auth_permission |
| auth_user |
| auth_user_groups |
| auth_user_user_permissions |
| blog_employee |
| django_content_type |
| django_session |
| django_site |
+----------------------------+
11 rows in set (0.00 sec)
mysql> desc blog_employee;
+-------+-------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-------+-------------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| name | varchar(20) | NO | | NULL | |
+-------+-------------+------+-----+---------+----------------+
本文出自 “流星宇” 博客,请务必保留此出处http://8789878.blog.51cto.com/8779878/1850748
原文地址:http://8789878.blog.51cto.com/8779878/1850748