How To: Send SQL commands to a database in VIM

A simple way of sending SQL to your database from everyone’s favourite editor Vim, without any plugins or macros.

Firstly we need to add a custom command to our .vimrc, open it up and add the following line, where:

  • CommandName - The name of your command
  • Username - The username for this database
  • Password - The password for this database
  • Database - The name of the database
:command -range=% CommandName :<line1>,<line2>w !mysql -uUsername -pPassword Database -t 

For example:

:command -range=% SendDB :<line1>,<line2>w !mysql -utest -ptest test -t 

That’s all the setting up we need. As you can see, after the exclamation mark is just the regular MySQL Command line tool and various options.

Fire up vim and start editing your sql.

# vim test.sql

As an example, here’s some simple SQL.

-- Drop existing table
DROP TABLE IF EXISTS `test`;

-- Create table
CREATE TABLE IF NOT EXISTS `test` (
    `test_id` INT(11) NOT NULL auto_increment,
    `name` VARCHAR(255) NOT NULL,
    PRIMARY KEY (`test_id`)
);

-- Add our data
INSERT INTO `test`(`name`) VALUES('dave');

-- Get it back out again
SELECT * FROM `test`;

If we’re happy with what we’ve written, while in command mode, type :SendDB, or whatever you called your command and hit enter. If it works, you’ll see something like this.

~/test.sql[+][sql] unix 
:SendDB
+---------+------+
| test_id | name |
+---------+------+
|       1 | dave | 
+---------+------+

Press ENTER or type command to continue

You can always add to the custom command, in particular piping the output to less can be effective for larger result sets.

Twitter Icon If you liked this post, you should follow me on twitter here
blog comments powered by Disqus

About

Photo of Dave Marshall

Dave Marshall is a Software Engineer living near Hull, England. He works on various personal projects and is the Technical Manager at Childcare.co.uk

Dave specialises in web application development for the LAMP stack, but always tries to choose a tool set that is most fit for purpose.

Dave is a Zend Certified Engineer and a Member of the British Computer Soceity.

Read more about Dave

Follow Dave: