Matt Cowley Matt Cowley - 2 years ago 84
MySQL Question

MySQL Create DB If Not Exists With File Import Command Line

So I'm using a command like:

mysql db < db.sql

But whenever I do this with a DB that doesn't already exist, it errors.

Is there a command flag to add to that to create the DB if it doesn't exist?
Or a line of code to insert into the start of the file?


Answer Source

So the solution for me was to write a PHP program to iterate through each db's sql file and do the following:

$mysqldir being where the mysql exe is installed too.
$db being the database name
$file being where the sql file is

$exec_str = "\"".$mysqldir."mysql\" -h localhost -u {username} -p{password} -e \"CREATE DATABASE IF NOT EXISTS `".$db."`\"";
system($exec_str, $status);
$exec_str = "\"".$mysqldir."mysql\" -h localhost -u {username} -p{password} ".$db." < \"".$file."\"";
system($exec_str, $status);

Basically: (Partially what @Drew answered with)

`database_name` < "C:\file\file2\db.sql"

from the mysql command line.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download