2017-08-27 152 views
0

我試圖導出MySQL 選擇查詢結果到CSV文件Python - 導出MySQL選擇查詢結果到CSV

爲此使用lambda,我的數據庫是在RDS。

我能夠連接並運行查詢。

但是,當我嘗試以CSV格式保存選擇查詢結果時,它不起作用。

需要python開發人員幫忙編寫這個腳本。

注意:Unicodewritter不適用於lambda。

lambda表達式:

import sys 
import logging 
import rds_config 
import pymysql 
#rds settings 
rds_host = "connection_link" 
name = rds_config.db_username 
password = rds_config.db_password 
db_name = rds_config.db_name 


logger = logging.getLogger() 
logger.setLevel(logging.INFO) 

try: 
    conn = pymysql.connect(rds_host, user=name, passwd=password, db=db_name, connect_timeout=5) 
except: 
    logger.error("ERROR: Unexpected error: Could not connect to MySql instance.") 
    sys.exit() 

logger.info("SUCCESS: Connection to RDS mysql instance succeeded") 

def handler(event, context): 
    """ 
    This function fetches content from mysql RDS instance 
    """ 

    item_count = 0 

    with conn.cursor() as cur: 
     cur.execute("create table Employee3 (EmpID int NOT NULL, Name varchar(255) NOT NULL, PRIMARY KEY (EmpID))") 
     cur.execute('insert into Employee3 (EmpID, Name) values(1, "Joe")') 
     cur.execute('insert into Employee3 (EmpID, Name) values(2, "Bob")') 
     cur.execute('insert into Employee3 (EmpID, Name) values(3, "Mary")') 
     conn.commit() 
     cur.execute("select * from Employee3") 

     for row in cur: 
      item_count += 1 
      logger.info(row) 
      #print(row) 
+1

問題更新 – SQLadmin

回答

0

下面的標準方法應該努力寫的所有行:

with conn.cursor() as cur: 
    cur.execute("create table Employee3 (EmpID int NOT NULL, Name varchar(255) NOT NULL, PRIMARY KEY (EmpID))") 
    cur.execute('insert into Employee3 (EmpID, Name) values(1, "Joe")') 
    cur.execute('insert into Employee3 (EmpID, Name) values(2, "Bob")') 
    cur.execute('insert into Employee3 (EmpID, Name) values(3, "Mary")') 
    conn.commit() 
    cur.execute("select * from Employee3") 

    res = cur.fetchall() 
    with open('output.csv','w') as fileout: 
     writer = csv.writer(fileout) 
     writer.writerows(res)   

如果您需要按行來處理線行,你可以使用writerow代替:

cur.execute("select * from Employee3") 

    with open('output.csv','w') as fileout: 
     writer = csv.writer(fileout) 
     for row in cur: 
      writer.writerow(row) 
+0

感謝您的回答,但輸出文件顯示0kb大小 – SQLadmin

+0

@Bhuvanesh您是否能夠在您的示例中記錄/打印查詢結果? – PRMoureu

+0

是的,當我使用打印(行)時,可以看到結果,其中顯示數據。 – SQLadmin