Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Haiz,

Is it possible to store a Perl hash into a MySQL column so that you can retrieve that row and assign it to a hash variabel?

Thanks :)

Replies are listed 'Best First'.
Re: Store hash in mysql
by Corion (Patriarch) on Jan 19, 2009 at 14:02 UTC

    Yes.

    Most likely you want to look at something like SQL::Abstract, unless you want to show us more code.

Re: Store hash in mysql
by jeffa (Bishop) on Jan 19, 2009 at 14:44 UTC

    Why do you think you need to do this? Normally, one would design a proper database schema and store each field of the hash in an appropriate row in the database table. Now that person can leverage the power of the database, rather than have to use Perl and risk doubling their work. Perhaps you are using this for a web browser session? Because without knowing what it is exactly that you are wanting to do -- giving advice to break normal form is not the best advice one can give. Rather ... one should not answer your question but instead ask you why you think you need to do this.

    jeffa

    L-LL-L--L-LL-L--L-LL-L--
    -R--R-RR-R--R-RR-R--R-RR
    B--B--B--B--B--B--B--B--
    H---H---H---H---H---H---
    (the triplet paradiddle with high-hat)
    

      I agree with Jeffa that in principle what you are asking to do sounds wrong. However, I don't know the circumstances and perhaps you need a temporary band-aid pending a better solution.

      In that case, you have a couple of options:

      1. Use Data::Dumper to flatten the hash into a scalar (string) and store the latter in a TEXT (or suitably large CHAR/VARCHAR) column and use eval to turn it back into a hash.
      2. Create an array of key value pairs (eg using each %hash), join them with a special char and store that in the text column so a simple split on the resultant string will give you the key, value array back which you can easily turn back into a hash.
Re: Store hash in mysql
by bradcathey (Prior) on Jan 19, 2009 at 15:41 UTC

    jeffa is right on.

    Working with hashes, both on the input side and select side is easy:

    my $stmt = 'INSERT INTO some_table (' . join(',', keys %data_to_insert +) . ') VALUES (' . join(',', ('?') x keys %data_to_insert) . ')'; $dbh->do( $stmt, undef, values %data_to_insert);

    and selecting it:

    my $stmt = 'SELECT * FROM some_table WHERE entry_id = ?'; my $row = $dbh->selectrow_hashref($stmt, undef, $entry_id); my $full_name = $row->{first_name'} . ' ' . $row->{last_name'};

    Be sure to see gmax's wonderful DBI Recipes.

    —Brad
    "The important work of moving the world forward does not wait to be done by perfect men." George Eliot