如何将mysql查询输出保存到名为(currentTime).csv的文件中

时间:2015-03-26 16:04:40

标签: python-2.7 csv mysql-workbench mysql-connector-python

我正在尝试将mysql查询的输出存储到文件中。我需要一个扩展名为.csv的文件,其名称应该是我当前的时间,例如: 2015-03-26 19:26:13.065000 .csv。
当我执行此查询时

conn=mysql.connector.connect(user='root',password='',host='localhost',database='ER_PC_NK')    
exe2 = conn.cursor()       
exe2.execute("""SELECT tbl_site.Site_name, State_Code, Country_Code,Street_Address, instrum_start_date, instrum_end_date, Comment INTO OUTFILE  'myrecord.csv' FIELDS TERMINATED BY '|' OPTIONALLY ENCLOSED BY '"' ESCAPED BY '\\\\' LINES TERMINATED BY '\\n' FROM tbl_site JOIN tbl_site_monit_invent ON site_id = tbl_Site_site_id""")

第一次保存了一个名为myrecord.csv的文件但是第二次没有。在互联网上长时间搜索后我发现它无法覆盖文件myrecord.csv,所以我决定将文件命名为currentTime.csv,这样做,我想尝试这样的事情:

    ss=DATE_FORMAT(NOW(),'_%Y_%m_%d_%H_%i_%s');

    SET @t1=1
    set @FOLDER = 'c:/tmp/';
    SET @PREFIX = 'orders';
    SET @EXT    = '.csv';

    SET @CMD = CONCAT("SELECT * FROM orders INTO OUTFILE '",@FOLDER,@PREFIX,@TS,@EXT,
        "' FIELDS ENCLOSED BY '\"' TERMINATED BY ';' ESCAPED BY '\"'",
        "  LINES TERMINATED BY '\r\n';");

    PREPARE statement FROM @CMD

但发现错误:用户定义的变量未定义,再次用Google搜索并找到user defined variables are available from Connector/NET version 5.2.2,而我正在使用MySQL Connector Python v2.0.3 for python v2.7

我很困惑,如果你有更好的解决方案,请告诉我。你的努力将会有很大的帮助。谢谢。

1 个答案:

答案 0 :(得分:0)

而不是用户定义的变量

import datetime
conn = mysql.connector.connect(user='root',password='',host='localhost',database='ER_PC_NK')    
exe2 = conn.cursor()       
exe2.execute(
   """SELECT tbl_site.Site_name, State_Code, Country_Code,
      Street_Address, instrum_start_date, instrum_end_date,
      Comment INTO OUTFILE  %s FIELDS TERMINATED BY '|' OPTIONALLY
      ENCLOSED BY '"' ESCAPED BY '\\\\' LINES TERMINATED BY '\\n' 
      FROM tbl_site JOIN tbl_site_monit_invent ON site_id = tbl_Site_site_id
   """, (str(datetime.datetime.now()),))