search
HomeDatabaseMysql TutorialPython+Django+SAE系列教程12-----配置MySQL数据库_MySQL

pythonDjango

因为SAE上支持的是Mysql,首先我们要在本地配置一个Mysql的环境 ,我在网上找到MySQL-python-1.2.4b4.win32-py2.7.exe,并双击 安装


选择典型安装


安装结束后,会弹出配置数据库的界面 :


然后输数据管理员密码:


最后是运行服务。


这个过程并不复杂,安装完成Mysql以后,系统会启动数据库服务,由于Mysql是用命令行控制的,想我这样懒的 人还是需要借助一个可视化 工具来管理,我选择MySQL-Front。

在网上找到MySQL_Front_Setup.1765185107.exe,双击安装就可以了,安装完打开软件:


这时我们会看到已经有的几个数据库:


我要开发程序首先,我们要建立一个数据库(右键 新建数据库),起名字为Mytestdb:


OK,这样我们就建立了一个空的数据库了,我先不着急在这里建表和表的关系。我们打算使用Django的模型的方式来建立:

首先我们修改一下

 setting.py,好让Django认识我们新建立的数据库:

ADMINS = (	('hemeng80', 'hemeng80@126.com'),)MANAGERS = ADMINSfrom os import environdebug = not environ.get("APP_NAME", "") if debug:	#LOCAL 	db_name = "MyTestDB"	name = "root"	pwd = "123456"	host = "127.0.0.1"	port = "3306"else: 	#SAE 	import sae.const	db_name = sae.const.MYSQL_DB	 	name = sae.const.MYSQL_USER	 	pwd = sae.const.MYSQL_PASS	 	host = sae.const.MYSQL_HOST		port = sae.const.MYSQL_PORT	 	host_s = sae.const.MYSQL_HOST_S DATABASES = {	'default': {		'ENGINE': 'django.db.backends.mysql', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'.		'NAME': db_name,					# Or path to database file if using sqlite3.		'USER': name,					# Not used with sqlite3.		'PASSWORD': pwd,				# Not used with sqlite3.		'HOST': host,					# Set to empty string for localhost. Not used with sqlite3.		'PORT': port,					# Set to empty string for default. Not used with sqlite3.	}}
上面的内容不需要多解释,你就会能明白,一种是在sae环境下的链接,一种是在本地的链接。

这时我们需要使用Django,生成一个模型,在命令行模式输入:

python manage.py startapp person

这个命令并没有输出什么,它只在 mysite 的目录里创建了一个 books 目录。 让我们来看看这个目录的内容:
person/
    __init__.py
    models.py
    tests.py
    views.py


这个目录包含了这个app的模型和视图。
使用你最喜欢的文本编辑器查看一下 models.py 和 views.py 文件的内容。 它们都是空的,除了 models.py 里有一个 import。这就是你Django app的基础。

目前我们的目录结构是这样的:


接下来我们来

编辑 person的models.py,来定义我们的数据模型:

models.py:

from django.db import models# Create your models here.class ClassRoom(models.Model):	name = models.CharField(max_length=30)	tutor = models.CharField(max_length=30)class Student(models.Model):	name = models.CharField(max_length=30)	sex = models.CharField(max_length=5)	age = models.IntegerField()	state_province = models.CharField(max_length=30)	qq = models.IntegerField()	classroom = models.ForeignKey(ClassRoom)
上面的数据模型比较简单,你一看就能明白,需要注意外键关系是这样建立的:
classroom = models.ForeignKey(ClassRoom)
为了让django认识我们新添加的App,还需要在setting.py中修改一些内容:
INSTALLED_APPS = (	'django.contrib.auth',	'django.contrib.contenttypes',	'django.contrib.sessions',	'django.contrib.sites',	'django.contrib.messages',	'django.contrib.staticfiles',	'person',	# Uncomment the next line to enable the admin:	# 'django.contrib.admin',	# Uncomment the next line to enable admin documentation:	# 'django.contrib.admindocs',)
这时,我们可以进入命令行程序,来检查一下我们的app是否正确:

python manage.py validate

如果没有问题的话,我们就可以使用这个模型来建立数据库中的表和表的关系了 ,命令行进入我们之前建立好的路径,输入:

python manage.py sqlall person


这样自动生成了,数据模型的建立表的SQl,语句,我们在mysql-front里面执行就可以自动创建数据库中的表了:


如果我们复制粘贴的话,这里面有一点问题,其中语句长的换行了,会执行不通过的,我们修改一下就行了:


在打开数据库,刷新看看,是不是我们表都自动创建了?


我们注意到Django自动创建了一个自增的主键!

既然我们在sae中开发,那么下面我就来看看如何在sae中创建一个Mysql的数据库,添加表的,找到sae的Mysql服务,点击初始化:


然后管理Mysql:


在这个里面执行以下我们刚才复制的sql语句创建表 :


这样我们就在本地和sae中创建了相同的表,并添加了响应的app,下一步就是如何对这个表进行最基本的操作了。

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
MySQL: Essential Skills for Beginners to MasterMySQL: Essential Skills for Beginners to MasterApr 18, 2025 am 12:24 AM

MySQL is suitable for beginners to learn database skills. 1. Install MySQL server and client tools. 2. Understand basic SQL queries, such as SELECT. 3. Master data operations: create tables, insert, update, and delete data. 4. Learn advanced skills: subquery and window functions. 5. Debugging and optimization: Check syntax, use indexes, avoid SELECT*, and use LIMIT.

MySQL: Structured Data and Relational DatabasesMySQL: Structured Data and Relational DatabasesApr 18, 2025 am 12:22 AM

MySQL efficiently manages structured data through table structure and SQL query, and implements inter-table relationships through foreign keys. 1. Define the data format and type when creating a table. 2. Use foreign keys to establish relationships between tables. 3. Improve performance through indexing and query optimization. 4. Regularly backup and monitor databases to ensure data security and performance optimization.

MySQL: Key Features and Capabilities ExplainedMySQL: Key Features and Capabilities ExplainedApr 18, 2025 am 12:17 AM

MySQL is an open source relational database management system that is widely used in Web development. Its key features include: 1. Supports multiple storage engines, such as InnoDB and MyISAM, suitable for different scenarios; 2. Provides master-slave replication functions to facilitate load balancing and data backup; 3. Improve query efficiency through query optimization and index use.

The Purpose of SQL: Interacting with MySQL DatabasesThe Purpose of SQL: Interacting with MySQL DatabasesApr 18, 2025 am 12:12 AM

SQL is used to interact with MySQL database to realize data addition, deletion, modification, inspection and database design. 1) SQL performs data operations through SELECT, INSERT, UPDATE, DELETE statements; 2) Use CREATE, ALTER, DROP statements for database design and management; 3) Complex queries and data analysis are implemented through SQL to improve business decision-making efficiency.

MySQL for Beginners: Getting Started with Database ManagementMySQL for Beginners: Getting Started with Database ManagementApr 18, 2025 am 12:10 AM

The basic operations of MySQL include creating databases, tables, and using SQL to perform CRUD operations on data. 1. Create a database: CREATEDATABASEmy_first_db; 2. Create a table: CREATETABLEbooks(idINTAUTO_INCREMENTPRIMARYKEY, titleVARCHAR(100)NOTNULL, authorVARCHAR(100)NOTNULL, published_yearINT); 3. Insert data: INSERTINTObooks(title, author, published_year)VA

MySQL's Role: Databases in Web ApplicationsMySQL's Role: Databases in Web ApplicationsApr 17, 2025 am 12:23 AM

The main role of MySQL in web applications is to store and manage data. 1.MySQL efficiently processes user information, product catalogs, transaction records and other data. 2. Through SQL query, developers can extract information from the database to generate dynamic content. 3.MySQL works based on the client-server model to ensure acceptable query speed.

MySQL: Building Your First DatabaseMySQL: Building Your First DatabaseApr 17, 2025 am 12:22 AM

The steps to build a MySQL database include: 1. Create a database and table, 2. Insert data, and 3. Conduct queries. First, use the CREATEDATABASE and CREATETABLE statements to create the database and table, then use the INSERTINTO statement to insert the data, and finally use the SELECT statement to query the data.

MySQL: A Beginner-Friendly Approach to Data StorageMySQL: A Beginner-Friendly Approach to Data StorageApr 17, 2025 am 12:21 AM

MySQL is suitable for beginners because it is easy to use and powerful. 1.MySQL is a relational database, and uses SQL for CRUD operations. 2. It is simple to install and requires the root user password to be configured. 3. Use INSERT, UPDATE, DELETE, and SELECT to perform data operations. 4. ORDERBY, WHERE and JOIN can be used for complex queries. 5. Debugging requires checking the syntax and use EXPLAIN to analyze the query. 6. Optimization suggestions include using indexes, choosing the right data type and good programming habits.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
Will R.E.P.O. Have Crossplay?
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools