waterlink / crystal-mysql

Basic mysql bindings for crystal.
MIT License
32 stars 11 forks source link

basic query about looping through query results #40

Open michaeldesu opened 8 years ago

michaeldesu commented 8 years ago

Hi

Sorry to ask a basic question (I'm new to Crystal).

my_query = "select firstname, lastname from table where lastname = 'smith'" a = conn.query puts a

gives the string array within an array, e.g.

[["Billy", "Smith"], ["Jane", "Smith"]]

Just to get a basic test working, I'm trying to loop through results using something like:

a.each do |result| puts result end

but I get an error 'undefined method 'each' for Nil.

Any tips would be appreciated. Thanks alot.

Cheers Michael.

waterlink commented 8 years ago

If you try outputting pp typeof(a), you will see that it is a union type: Array(Mysql::Types)?. Question mark at the end is the same as |Nil, which, effectively, means, that a is an array of mysql types, or it is a nil.

When compiler fails with Nil error, it tells you that it doesn't know what to do, when the value will be Nil at runtime. You can provide it with information by verifying the type:

a = conn.query(...)
if a
  a.each { ... }
else
  puts "Couldn't make query :("
end

If you are convinced, that value can not be nil, story is simpler: use not_nil!:

a = conn.query(...)
a.not_nil!.each { ... }
michaeldesu commented 8 years ago

Thanks alot for your generous explanation. Much appreciated. Please consider to make some tutorials on your site. Your Crystal experience would be appreciated by new users.

incognick commented 8 years ago

Yes, thank you. I ran into this same exact issue.