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

-- Create table
    `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 
| 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.