Yes.
Most likely you want to look at something like SQL::Abstract, unless you want to show us more code.
| [reply] |
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.
| [reply] |
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:
-
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.
-
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.
| [reply] |
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
| [reply] [d/l] [select] |