600字范文,内容丰富有趣,生活中的好帮手!
600字范文 > Ruby on Rails 创建开发用的MYSQL数据库

Ruby on Rails 创建开发用的MYSQL数据库

时间:2022-10-19 06:49:06

相关推荐

Ruby on Rails 创建开发用的MYSQL数据库

在《Ruby on Rails,使用关系数据库简介》中我们简要浏览了一下关系数据库的最基本概念,这里我们动手创建一个Rails项目可以使用的数据库。Rails可以与DB2、MySQL、Oracle、Postgres、Firebird以及 SQL Server数据库一起工作。新版Rails已经使用SQLite3作为缺省数据库类型了,但是为了管理方便和通用性的考虑,我依旧使用MySQL来作为数据库。在开始之前请先确保MySQL数据库安装完毕并且将环境变量设置好。

检查MySQL安装正确性。

cmdC:\Windows\system32>mysql --version mysql Ver 14.14 Distrib 5.5.17, for Win64 (x86)

使用root用户登录MySQL,安装数据库的时候设置了root的密码,所以登录的时候需要增加-p命令:

cmdC:\Windows\system32>mysql -u root -p Enter password: **** Welcome to the MySQL monitor. Commands end with ; or \g. Your MySQL connection id is 5713 Server version: 5.5.17 MySQL Community Server (GPL) Copyright (c) 2000, , Oracle and/or its affiliates. All rights reserved. Oracle is a registered trademark of Oracle Corporation and/or its affiliates. Other names may be trademarks of their respective owners. Type 'help;' or '\h' for help. Type '\c' to clear the current input statement. mysql>

回顾一下使用命令行管理MySQL的命令:

浏览现有数据库--SHOW DATABASES;

创建数据库--CREATE DATABASE db_name;

删除数据库--DROP DATABASE db_name;

在MySQL中命令并不强制要求将命令大写,但是的确推荐这么做看起来更清晰。

SHOW DATABASES;显示了我的数据库中当前的数据库列表。其中simple_site_development是为之前的例子项目创建的。参考《Ruby on Rails,创建一个最简单的站点》。

sqlmysql> SHOW DATABASES; +-------------------------+ | Database| +-------------------------+ | information_schema| | mysql | | performance_schema| | simple_site_development | +-------------------------+ 4 rows in set (0.00 sec)

因为后面我想做一个简单的CMS站点,所以我把数据库的名字叫做“simple_cms”。Rails可以为项目在不同的生命周期指定不同的数据库,开发阶段使用simple_cms_development。

sqlmysql> CREATE DATABASE simple_cms_development; Query OK, 1 row affected (0.00 sec)

拥有良好习惯的作法是在数据库建立完毕之后向其分配用户,而不是一直使用root用户登录和管理数据。

我们需要创建一个用户,并且向这个用户分配权限。权限管理的相关命令有:

GRANT ALL PRIVILEGES ON db_name.* TO ’username‘ @ 'localhost' IDENTIFIED BY 'password';其中db_name,username,localhost和password分别是数据库名,用户名,主机名,和密码。注意’abbuggy‘并不是一个好的密码。

sqlmysql> GRANT ALL PRIVILEGES ON simple_cms_development.* TO 'abbuggy'@'localhost' IDENTIFIED BY 'abbuggy'; Query OK, 0 rows affected (0.18 sec)

重新使用新的用户名登录一遍,成功。

cmdC:\Windows\system32>mysql -u abbuggy -p Enter password: ******* Welcome to the MySQL monitor. Commands end with ; or \g. Your MySQL connection id is 5728 Server version: 5.5.17 MySQL Community Server (GPL) Copyright (c) 2000, , Oracle and/or its affiliates. All rights reserved. Oracle is a registered trademark of Oracle Corporation and/or its affiliates. Other names may be trademarks of their respective owners. Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

使用刚刚创建的simple_cms_development数据库。

sqlmysql> use simple_cms_development; Database changed

到此为止一切顺利,下一篇将介绍如何在Rails中配置并使用数据库。

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。