Parameterizing file name in MYSQL LOAD DATA INFILE

后端 未结 4 1508
别跟我提以往
别跟我提以往 2020-12-11 18:53

Is there a way to dynamically specify a file name in the LOAD DATA INFILE? Can it be parameterized like for instance (syntax may be incorrect) LOAD DATA INFILE \'$filename\'

相关标签:
4条回答
  • 2020-12-11 19:05

    Or you can make a temporary copy of the file (BATCH example):

    LOAD_DATA.bat

    COPY %1 TempFileToLoad.csv
    mysql --user=myuser --password=mypass MyDatabase < ScriptLoadMyDatabase.sql
    DEL TempFileToLoad.csv
    

    the SQL (for info) :

    ScriptLoadMyDatabase.sql

    load data infile 'TempFileToLoad.csv' IGNORE
    into table tLoad
    FIELDS TERMINATED BY ';' OPTIONALLY ENCLOSED BY '"'
    lines terminated by '\r\n'
    IGNORE 1 LINES
    (@DateCrea, NomClient, PrenomClient, TypeMvt, @Montant, NumeroClient)
    set DateCrea = str_to_date(@DateCrea, '%Y-%m-%d'), Montant = (round(@Montant / 1000)*2) ;
    

    And finished to put a link to the BAT file in SendTo windows folder.

    0 讨论(0)
  • 2020-12-11 19:13

    A citation from MySQL documentation:

    The LOAD DATA INFILE statement reads rows from a text file into a table at a very high speed. The file name must be given as a literal string.

    That means that it can not be a parameter of a prepared statement. But no one forbids to make the string interpolation while the statement is just a string in your PHP code.

    0 讨论(0)
  • 2020-12-11 19:18

    If you're asking if it can be used in a script; you can do some thing like this with php:

    <?php
    $mysqli = new mysqli("host", "user", "pwd", "db");
    /* check connection */
    if (mysqli_connect_errno()) {
        printf("Connect failed: %s\n", mysqli_connect_error());
        exit();
    }
    
    
    $sql = "CREATE TABLE number1 (id INT PRIMARY KEY auto_increment,data TEXT)";
    if ($result = $mysqli->query($sql)) {
    } else {
    printf("<br>%s",$mysqli->error);
    
    }
    
    $host  = $_SERVER['HTTP_HOST'];
    $uri   = rtrim(dirname($_SERVER['PHP_SELF']), '/\\');
    $filename = "data.csv";
    
    $sql = "LOAD DATA LOCAL INFILE '$host$uri$filename' INTO TABLE number1";
    if ($result = $mysqli->query($sql)) {
    
    } else {
    printf("<br>%s",$mysqli->error);    
    }
    // Close the DB connection
    $mysqli->close();
    
    exit;
    %>
    

    If the file is in the same folder as the script just use $filename a instead of $host$uri$filename. I put this together quick from a couple scripts I'm using, sorry if it doesn't work without debug, but it should be pretty close. It requires mysqli.

    0 讨论(0)
  • 2020-12-11 19:21

    Unfortunately, this feature is not yet supported in MySQL and is currently listed as bug/feature request #39115 http://bugs.mysql.com/bug.php?id=39115

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