您好,登錄后才能下訂單哦!
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 | |
+-------+-------------+------+-----+---------+----------------+
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。