简体   繁体   中英

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. 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.

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.

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}'})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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