【问题标题】:Python - Export MySQL select query results to CSVPython - 将 MySQL 选择查询结果导出到 CSV
【发布时间】:2018-02-04 19:07:54
【问题描述】:

我正在尝试导出 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)

【问题讨论】:

  • 问题已更新

标签: python mysql csv lambda


【解决方案1】:

以下标准方法应该可以写入所有行:

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)

【讨论】:

  • 感谢您的回答,但输出文件显示 0kb 大小
  • @Bhuvanesh 你能在你的例子中记录/打印查询结果吗?
  • 是的,当我使用 print(row) 时,我可以看到结果,它显示了数据。
  • @Bhuvanesh 数据使用什么语言/编码?
  • 也许值得一试unicodecsv,或者指定with open('output.csv','w', encoding='utf-8')
猜你喜欢
  • 2017-12-31
  • 2013-05-13
  • 1970-01-01
  • 1970-01-01
  • 2015-06-29
  • 1970-01-01
  • 2014-05-29
  • 2016-11-10
  • 1970-01-01
相关资源
最近更新 更多