Execute sql query from sql file

后端 未结 4 869
野的像风
野的像风 2021-01-07 10:09

I want to include all tables from a database \"shop\" to mydatabase newshop. I export that \"shop\" database, and now it is named as shop.sql. Is t

相关标签:
4条回答
  • 2021-01-07 10:49

    Here's the code you might be interested in:

    <?php
    
      $dbhost = 'localhost';
      $dbuser = 'root';
      $dbpass = 'password';
      $db = 'newshop';
      $file =dirname(__FILE__).'\\'.'shop.sql';
      $mySQLDir='"C:\\Program Files\\MySQL\\MySQL Server 5.1\\bin\\mysql.exe"';
    
    
    
        if ($dbpass != '') {
            $cmd = $mySQLDir.' -h '.$dbhost.' --user='.$dbuser.' --password='.$dbpass.' < "'.$file.'"';
    
        } else {
            $cmd = $mySQLDir.' -h '.$dbhost.' --user='.$dbuser.' < "'.$file.'"';
        }
    
         echo $cmd;  
    
       exec('"'.$cmd.'"',$out ,$retval);
       echo "\n";
        echo ($retval);
    
    ?>
    
    0 讨论(0)
  • 2021-01-07 11:06

    I think what you need might be:

    $ mysql -u $USERNAME -p < "$SQLFILENAME"

    Where $USERNAME is the user name of mysql like root and $SQLFILENAME is the name of the sql file ('shop.sql' in this case).

    The above command will ask you to type in password. If you don't want to do that every time, you can use '--password=$PASSWORD' BUT be careful. This password may be saved in history and it might be in the wrong hand (If you run it from PHP, it may not be a problem).

    OR you can use mysqli to run it.

    <?php
    $link = mysqli_connect("localhost", "my_user", "my_password", "world");
    
    /* check connection */
    if (mysqli_connect_errno()) {
        printf("Connect failed: %s\n", mysqli_connect_error());
        exit();
    }
    
    $query = file_get_contents("shop.sql");
    
    /* execute multi query */
    if (mysqli_multi_query($link, $query))
         echo "Success";
    else 
         echo "Fail";
    ?>
    

    Hope this helps.

    0 讨论(0)
  • 2021-01-07 11:10

    Considering this question is tagged with PHP, here's how you could do it:

    mysql_query('USE newshop');
    $queries = file('shop.sql');
    while(list($i, $query) = each($queries)){
        $query = trim($query, ';');
        if(!empty($query) && $query != 'USE shop'){
            @mysql_query($query);
        }
    }
    

    Make sure "USE shop" in the if statement matches whatever syntax is used in the SQL file. For instance, you might need to make it USE 'shop' or USE schemaname.shop. Or, if there's no USE command in there at all, you can just take that condition right out.

    0 讨论(0)
  • 2021-01-07 11:14
    >>> mysql -u username -p
    >>> show databases;
    >>> use foo;
    >>> source /home/mannu/file.sql
    

    I believe that's what you're looking for? Or did I misunderstand?

    0 讨论(0)
提交回复
热议问题