Rails 判断mysql数据库是否存在

Posted by wxianfeng Wed, 15 Feb 2012 20:56:00 GMT

环境: Rails 3.0.3
Rails中判断表是否存在,表的某个字段是否存在都提供了API,但是如何判断数据库存在,没有提供api

可以使用下面的方法判断出来:

> ActiveRecord::Base.connection.execute("USE INFORMATION_SCHEMA") # 连接mysql INFORMATION_SCHEMA 数据库
>ActiveRecord::Base.connection.execute("SELECT SCHEMA_NAME FROM INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME = 'db'").to_a
=>[["db"]] # 存在db
>ActiveRecord::Base.connection.execute("SELECT SCHEMA_NAME FROM INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME = 'db1'").to_a
=>[] # 不存在db1

This entry was posted on Wed, 15 Feb 2012 20:56:00 GMT and Posted in , . You can follow any any response to this entry through the Atom feed. You can leave a comment or a trackback from your own site.

Tags ,


Trackbacks

Use the following link to trackback from your own site:
http://wxianfeng.com/trackbacks?article_id=225

Comments

  1. Avatar
    Φθηνά καράβια almost {{count}} years ago:

    Wonderful goods from you, man. I’ve understand your stuff previous too annd
    you are just extremely magnificent. I really like what you’ve acquired here,
    really like what you are stating and the way in which you say
    it. You make it enjoyable and you still take care of to keep it sensible.
    I can not wait to read much more from you. This is actually a terrific
    website.

  2. Avatar
    Φθηνά καράβια almost {{count}} years ago:

    Wonderful goods from you, man. I’veunderstand your stuff previous too and
    you are just extremely magnificent. I really like what
    you’ve acquired here, really like what yyou are stating andd the way in which
    you say it. You make it enjoyable and you still take
    care of to keep it sensible. I can not wait to read much more from you.

    This is achtually a terrific website.

Leave a comment