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

Is it possible to take a hash and insert it into MySQL, while "mapping" the keys to database field names? If so, I would need to insert a few other values in addition to what I have in the hash? Thanks!
$VAR1 = { 'Vlan212' => { 'inputQueueDrop' => '468723', 'inputQueueFlushes' => '54735', 'status1' => 'up' }, 'Vlan215' => { 'inputQueueDrop' => '80366', 'inputQueueFlushes' => '80366', 'lateErrors' => '3452', 'runts' => '234', } };

Replies are listed 'Best First'.
Re: Inserting hash keys to MySQL field names using DBI
by bart (Canon) on Dec 16, 2007 at 10:07 UTC
    Yes. Take a look at DBIx::Simple, which is a layer over DBI. You really don't need a lot of code:
    use DBIx::Simple; $db = DBIx::Simple->connect(...); # just as with DBI $db->insert($table, \%hash);
    See SQL::Abstract for the syntax, which DBIx::Simple uses for its implementation.

    Behind the curtains, it builds and prepares statements using placeholders, and it keeps a pool of cached statement holders, so repeated use of calls will be quite efficient: it'll try to avoid preparing the same statement over and over again.

Re: Inserting hash keys to MySQL field names using DBI
by CountZero (Bishop) on Dec 16, 2007 at 13:06 UTC
    There is a problem with a direct mapping between database fields and hash keys if you have a multi-level hash such as a HoH.

    Every record is one line of many field = value objects and these can be fairly easily mapped to and from a hash.

    However, when your hash has multiple levels you need to somehow collapse your structure into one line.

    With a hash of hashes as you have, this is still not too difficult: the first level ("Vlan212", "Vlan215", ...) will become the value of the key field of your record and the structure and contents of your records will be:

    Key inputQueueDrop inputQueueFlushes status1 lateErrors runts Vlan212 468723 54735 up Vlan215 80366 80366 3452 234
    Do have a look at modules such as DBIx::Class, the so-called "Object Relational Mappers", which make using databases much easier.

    CountZero

    A program should be light and agile, its subroutines connected like a string of pearls. The spirit and intent of the program should be retained throughout. There should be neither too little or too much, neither needless loops nor useless variables, neither lack of structure nor overwhelming rigidity." - The Tao of Programming, 4.1 - Geoffrey James

Re: Inserting hash keys to MySQL field names using DBI
by fmerges (Chaplain) on Dec 16, 2007 at 12:05 UTC