繁体   English   中英

检查mysql表是否已存在

[英]Check if mysql table already exist

我使用activerecord连接到mysql数据库并在连接后创建一个表。 到目前为止它工作得很好,问题是我不知道如何检查表是否已经存在。 我认为它适用于table.exist? 但不知怎的,我没有......所以这就是我到目前为止所得到的:

ActiveRecord::Base.establish_connection(
        :adapter => "mysql",
        :host => "localhost",
        :username => "my-username",
        :password => "my-password",
        :database => "my-db",
        :encoding => "UTF8"
    )

    # How to check if it exists already? table_name.table.exist? doesnt really work...
    name = "my_table"
if name.!table.exist?
    ActiveRecord::Schema.define do
        create_table :"#{name}" do |table|
            table.column :foo, :string
            table.column :bar, :string
        end
    end
else
puts "Table exist already..."
end
    # Create ActiveRecord object for the mysql table
    class Table < ActiveRecord::Base
        set_table_name "#{name}"
    end

您需要在数据库连接上使用#tables方法。

unless ActiveRecord::Base.connection.tables.include? name
  ActiveRecord::Schema.define do
    create_table :"#{name}" do |table|
      table.column :foo, :string
      table.column :bar, :string
    end
  end
end

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM