DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Michael has posted 7 posts at DZone. View Full User Profile

Making MySQL Executable Scripts.

12.04.2006
| 14760 views |
  • submit to reddit
        Use "here document" statements to build complex script files with embedded SQL statements via the mysql utility.

#! /usr/bin/env bash

# execute some bash scripting commands here

mysql mydatabase <<SQL_ENTRY_TAG_1
SELECT * 
  FROM mytable 
  WHERE somecondition='somevalue';
SQL_ENTRY_TAG_1

# execute other bash scripting commands here

mysql mydatabase <<SQL_ENTRY_TAG_2
SELECT *
  FROM myothertable
  WHERE someothercondition='someothervalue';
SQL_ENTRY_TAG_2

Note that being in a bash script means that you can expand $-variables inside the SQL code directly.  This is, however, not advised unless you can be sure that only trusted, competent people will run your code.  Otherwise you'll be facing SQL injection attacks.