重庆分公司,新征程启航
为企业提供网站建设、域名注册、服务器等服务
Python Django连接数据库
10年积累的成都做网站、成都网站设计经验,可以快速应对客户对网站的新想法和需求。提供各种问题对应的解决方案。让选择我们的客户得到更好、更有力的网络服务。我虽然不认识你,你也不认识我。但先制作网站后付款的网站建设流程,更有正安免费网站建设让你可以放心的选择与我们合作。
一、安装数据库
# 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 | |
+-------+-------------+------+-----+---------+----------------+