简体   繁体   English

使用 SQL 服务器使用 Pandas 的数据创建 CSV 文件

[英]Creating a CSV file using data from SQL Server using Pandas

I have a SQL Server database that is holding material data that I need to get the total usage of a material out into a CSV file.我有一个 SQL 服务器数据库,它保存我需要的材料数据,以便将材料的总使用量输出到 CSV 文件中。 I can get all of the data out and print it to the terminal without issue but when trying to use Pandas and get it into a CSV with named columns all I get is Pandas rewriting the first row with each line that comes out of SQL. I have not gotten Pandas to create the CSV but I can see it in terminal re-writing that first row for each line that comes from SQL. I am using a function to get each row out of SQL.我可以获取所有数据并将其打印到终端而不会出现问题,但是当尝试使用 Pandas 并将其放入具有命名列的 CSV 时,我得到的只是 Pandas 用来自 SQL 的每一行重写第一行。我还没有得到 Pandas 来创建 CSV,但我可以在终端中看到它为来自 SQL 的每一行重写第一行。我正在使用 function 来获取 SQL 中的每一行。

import pyodbc
import pandas as pd
def checkmaterials():

    server_name = '********'
    db_name = '********'
    username = '********'
    password = '********'

    conn = pyodbc.connect('DRIVER={ODBC Driver 17 for SQL Server};SERVER=' + server_name + '\WEMSQLEngine' ';DATABASE=' + db_name + ';UID=' + username + ';PWD=' + password + '')
    #if conn is not None:
        #print('Connected to SQL')

    cursor = conn.cursor()
    query = cursor.execute("SELECT * FROM MATERIAL")
    data = query.fetchall()
    for row in data:
      MatCode = row[0]
      IngName = row[1]
      Receipt1 = row[4]
      Usage1 = row[6]

      #This print statement prints each line to terminal and does the math to get usage correctly
      #print (f'Daily {MatCode} {IngName} {dailyusage(Usage1,Receipt1)} lbs')

      df = pd.DataFrame(query, columns=[MatCode,IngName,Receipt1,Usage1])
      #print (df)

def dailyusage(Usage1, Receipt1):
    return Usage1 - Receipt1

checkmaterials()

Instead of using Pandas and dataframes I ended up using Python's built in CSV function.我没有使用 Pandas 和数据框,而是使用 Python 内置的 CSV function。

file_exists = os.path.isfile(f'{Filename}.csv')
    with open(f'{Filename}.csv', 'a+', newline='') as csvfile:
        fieldnames = ['column 1', 'column 2','Column 3']
        writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
        if not file_exists:
            writer.writeheader()
        writer.writerow({'Column 1' f'{data variable}', 'Column 2': f'{data variable}', 'Column 3': f'{data variable}'})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM