Controlling MySQL on Unix

Problem

The standard Ruby database interfaces assume you e connecting to a preexisting database, and that you already have access to this database. You want to create and administer MySQL databases from within Ruby.

Solution

Sam Ruby came up with an elegant solution to this problem. The mysql method defined below opens up a pipe to a MySQL client program and sends SQL input to it:

	def mysql(opts, stream)
	 IO.popen("mysql #{opts}", w) { |io| io.puts stream }
	end

You can use this technique to create, delete, and administer MySQL databases:

	mysql -u root -p[password], <<-end
	 drop database if exists website_db;
	 create database website_db;
	 grant all on website_db.* to #{`id -un`.strip}@localhost;
	end

Discussion

This solution looks so elegant because of the <<-end declaration, which allows you to end the string the same way you end a code block.

One shortcoming of this solution is that the IO.popen call opens up a one-way communication with the MySQL client. This makes it difficult to call SQL commands and get the results back. If thats what you need, you can use IO.popen interactively; see Recipe 23.1.

See Also

  • Recipe 23.1, "Scripting an External Program"


Strings

Numbers

Date and Time

Arrays

Hashes

Files and Directories

Code Blocks and Iteration

Objects and Classes8

Modules and Namespaces

Reflection and Metaprogramming

XML and HTML

Graphics and Other File Formats

Databases and Persistence

Internet Services

Web Development Ruby on Rails

Web Services and Distributed Programming

Testing, Debugging, Optimizing, and Documenting

Packaging and Distributing Software

Automating Tasks with Rake

Multitasking and Multithreading

User Interface

Extending Ruby with Other Languages

System Administration



Ruby Cookbook
Ruby Cookbook (Cookbooks (OReilly))
ISBN: 0596523696
EAN: 2147483647
Year: N/A
Pages: 399

Flylib.com © 2008-2020.
If you may any questions please contact us: flylib@qtcs.net