2

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?

TIA.

2 Answers 2

3

do you mean like these two lines?

create schema if not exists myNewDb;
use myNewDb;    -- make it the active one

The second command will select the db (whether or not it just created it).

Sign up to request clarification or add additional context in comments.

2 Comments

Yes I ended up doing somethine similar. I got PHP to run first the mysql command with CREATE DATABASE IF NOT EXISTS $dbname then I got it to run again with my original command and that fixed my issues.
Great. Perhaps you can check mark it as Answered then. Perhaps others will find it helpful, even though you asked the question.
2

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)

CREATE DATABASE IF NOT EXISTS `database_name`
`database_name` < "C:\file\file2\db.sql"

from the mysql command line.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.