Finding out if a Mysql database contains a certain table

Discussion in 'Ruby' started by ngw, Feb 19, 2006.

  1. ngw

    ngw Guest

    Hi *,
    I need to find out if a MySQL db contains a certain table, if not I have
    to create it.
    I'm using the SHOW TABLES instruction that returns a Mysql::Result
    object, but after that I'm stuck, I don't know how to process the
    resultset without writing awful code :p
    I mean, I can resolve the problem by using a "state" variable inside a
    block and turn it to true if it finds the table, but I guess there's a
    more appropriate way to handle this kind of problems.

    result = dbh.query("SELECT * FROM album")
    foo = false
    result.each {|row| foo = true if row.include?("Killing Joke")}
    if foo == true
    puts "HA!"
    end
    result.free

    This is the code I have now, UGH !

    TIA,
    ngw
    ngw, Feb 19, 2006
    #1
    1. Advertising

  2. ngw

    Caleb Tennis Guest

    On Feb 19, 2006, at 11:28 AM, ngw wrote:

    > Hi *,
    > I need to find out if a MySQL db contains a certain table, if not I
    > have
    > to create it.
    > I'm using the SHOW TABLES instruction that returns a Mysql::Result
    > object, but after that I'm stuck, I don't know how to process the
    > resultset without writing awful code :p
    > I mean, I can resolve the problem by using a "state" variable inside a
    > block and turn it to true if it finds the table, but I guess there's a
    > more appropriate way to handle this kind of problems.


    A show tables command just returns a query of table names, 1 per row.

    I'm not sure if you need to do something more complex, but in MySQL
    it's valid to do:

    CREATE TABLE IF NOT EXISTS

    Caleb
    Caleb Tennis, Feb 19, 2006
    #2
    1. Advertising

  3. D=C5=88a Nede=C4=BEa 19 Febru=C3=A1r 2006 18:31 Caleb Tennis nap=C3=ADsal:
    > A show tables command just returns a query of table names, 1 per row.
    >


    Sidenote: SHOW TABLES is a MySQLism, so watch out it you can't rule out the=
    =20
    data will be migrated to another DB.

    David Vallner
    David Vallner, Feb 19, 2006
    #3
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. James Dyer
    Replies:
    5
    Views:
    643
  2. Replies:
    4
    Views:
    340
    Roedy Green
    Nov 24, 2005
  3. julian
    Replies:
    8
    Views:
    448
    Avatar
    Apr 6, 2006
  4. Merlin
    Replies:
    2
    Views:
    93
    Evertjan.
    Oct 30, 2005
  5. Sam
    Replies:
    4
    Views:
    72
    Mark Lawrence
    Jan 17, 2014
Loading...

Share This Page