七、Python Django连接数据库
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 | |
+-------+-------------+------+-----+---------+----------------+
免责声明:
① 本站未注明“稿件来源”的信息均来自网络整理。其文字、图片和音视频稿件的所属权归原作者所有。本站收集整理出于非商业性的教育和科研之目的,并不意味着本站赞同其观点或证实其内容的真实性。仅作为临时的测试数据,供内部测试之用。本站并未授权任何人以任何方式主动获取本站任何信息。
② 本站未注明“稿件来源”的临时测试数据将在测试完成后最终做删除处理。有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341