简体   繁体   中英

Extract unique values from an SQL database to excel using python

I am quite new to python and trying to work on a project that requires me to extract data from an SQL(.db) database and output this data into an excel file.

My database File has a lot of data but the structure I have managed to print is as follows

Run ID | Environment

1           52

2           52

3           52

4           52

5           72

6           72

7           72

8           72
....

now I need to be able to output these values to an excel spreadsheet like this,

52|72|92|112|132

Below is my current code and it allows me to output

52|52|52|52|72|72|72|72

a is the c.fetchall() from the module access database Any help is appreciated

Access_Database_Module.Access_Database(DB)    
x = 2
DBcommand = "SELECT * FROM " + a[x][0]
print(a[x][0]) 
c.execute(DBcommand)
y = c.fetchall()    

x = y

workbook = xls.Workbook('Environment.xlsx')
worksheet = workbook.add_worksheet('Environment Direction')

rowNum = 0 
colNum = 1

workbook = xls.Workbook('Environment.xlsx')
worksheet = workbook.add_worksheet('Environment Direction')

for item in y:
    while colNum == colNum + 1 :
        colNum 
    worksheet.write(rowNum, colNum, item[14])
    colNum += 1 

workbook.close()

you need to change your query as follows:

DBcommand = "SELECT distinct [Environment] FROM " + a[x][0]

This will return unique values which is what you are looking for

Do you want to remove duplicates from your database column and store it in a excel? If it so, then the below code may help you.

import pandas as pd
import sqlite3

# get DB connection
con = sqlite3.connect("your DB connection")

# Read sqlite query results into a pandas DataFrame
df = pd.read_sql_query("SELECT * from yourDB", con)

# verify that result of SQL query is stored in the dataframe
print(df.head())

con.close()

# if you want to remove duplicate based on particular column then do this
df.drop_duplicates(subset=[column_name],inplace=True)
# else do this
df.drop_duplicates(inplace=True)

# export to Excel file
df.to_excel("filename.xlsx",index=False)

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