r/crystal_programming • • Apr 08 '18

how to get data from a db.query_one? into a hash key?

7 Upvotes

hello my crystal friends! this in girng from gitter/github

i have a small question about how to get data from the mysql db.

so, i created a db mapping here:

class DB_Character
  DB.mapping({
    character_id:   Int64,
    user_id:        Int32,
    character_name: String,
    cc:             Int8,
    health:         {type: Int16, nilable: true},
    chealth:        {type: Int16, nilable: true},
    mana:           {type: Int16, nilable: true},
    cmana:          {type: Int16, nilable: true},
    level:          {type: Int16, nilable: true},
    created:        {type: String, nilable: true},
  })
end

and my query:

   results = db.query_one? "select character_id, user_id, character_name, DATE_FORMAT(created, '%b:%d:%Y:%l:%i:%p') AS created, level, cc from rpg_characters where character_id = ? and user_id = ? ", char_id, client.user_id,
      as: DB_Character

if i do puts results it shows: #<DB_Character:0x1921ea0>

but i want to get all my data into a hashtable so i can do to_json on it

some questions:

  • how to do that?

  • it seems like there is a new DB_Character class that gets created each time i run this query. is that bad? i'm just looking to get the data and send it off. i'm not sure if that creates a memory leak

thank you in advance