现在的位置: 首页 > 综合 > 正文

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

2013年06月23日 ⁄ 综合 ⁄ 共 2440字 ⁄ 字号 评论关闭

http://blog.csdn.net/abbuggy/article/details/7647110

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

检查MySQL安装正确性。

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

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

C:\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, 2011, 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,创建一个最简单的站点》

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

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

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

拥有良好习惯的作法是在数据库建立完毕之后向其分配用户,而不是一直使用root用户登录和管理数据。
我们需要创建一个用户,并且向这个用户分配权限。权限管理的相关命令有:
GRANT ALL PRIVILEGES ON db_name.* TO ’username‘ @ 'localhost' IDENTIFIED BY 'password';其中db_name,username,localhost和password分别是数据库名,用户名,主机名,和密码。注意’abbuggy‘并不是一个好的密码。

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

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

C:\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, 2011, 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>

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

mysql> use simple_cms_development;  
Database changed  
mysql>

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


http://blog.csdn.net/abbuggy/article/details/7647110

抱歉!评论已关闭.