UTF-8 MySQL connections with Ruby

From A2Wiki

Jump to: navigation, search

Rails

In order to send, receive and display Unicode characters properly in Ruby on Rails using MySQL, there are 3 steps:

1. Change your database, table and column character sets.

ALTER DATABASE `database_name` DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci;
ALTER TABLE `table_name` DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci;
ALTER TABLE `table_name` CHANGE `column_name` `column_name` TEXT CHARACTER SET utf8 COLLATE utf8_general_ci;

2. Configure Rails to connect with UTF-8 encoding by adding the following line to your database.yml configuration:

encoding: utf8

3. Display your pages as UTF-8 content. Add the following meta tag to the head of each of your pages:

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />

Ruby

If you're not using Rails but you're using the Ruby MySQL module to connect, you'll need to set the encoding of the connection before you can pass Unicode characters to your database. Use the following connection string:

#!/usr/bin/ruby

require 'rubygems'
require 'mysql'

db = Mysql.init
db.options(Mysql::SET_CHARSET_NAME, 'utf8')
db.real_connect('host', 'user', 'password', 'database', 3306, '/usr/local/lib/mysql.sock')
db.query("SET NAMES utf8")

Also be sure to change the character sets of your database, tables and columns.

Personal tools