Data type of MySQL result fields is always string

I have a trouble with MySQL select result fields' data type definition -
all fields' type is always string. For example, I call this code:

ActiveRecord::Base.connection.select_all('SELECT COUNT(*) count FROM
table').first['count']

The result will always string, but it must be integer. There is the same
problem with all numeric fields of table - they always strings too.

Does anybody know, how to fix this data type definition problem with
MySQL? I have mysql-2.7 gem. Thanks.

That is because you are not using the rails way of working. If you pass custom sql requests to the database, the return type will always be a string and you need to convert the value yourself (.to_i).

But in your case I have no clue why you are not using ActiveRecord like you should:

MyModel.count

Best regards

Peter De Berdt

Peter De Berdt wrote:

That is because you are not using the rails way of working. If you
pass custom sql requests to the database, the return type will always
be a string and you need to convert the value yourself (.to_i).

It's rather curiously, because Oracle driver for Ruby On Rails solves my
problem successfully (I use Rails + Oracle in my work project) - there
isn't any problem with data type definition. It's very pity, that MySQL
adapter works so simple...

Nevertheless, thanks.

All I was pointing out was that you are using raw sql queries while using such a huge library as ActiveRecord which does it all for you in a more Ruby-ish way. And the added bonus is that you don’t have to worry about the database backend because of the database abstraction you get for free.

Raw SQL queries do have their place though (very complex queries or occasional optimizations), but if you can avoid them, you should.

Best regards

Peter De Berdt