使用python从SQL数据库中提取excel的唯一值

时间:2017-07-21 03:31:21

标签: python excel sqlite

我是python的新手,并尝试处理一个项目,该项目要求我从SQL(.db)数据库中提取数据并将此数据输出到Excel文件中。

我的数据库文件有很多数据,但我设法打印的结构如下

Run ID | Environment

1           52

2           52

3           52

4           52

5           72

6           72

7           72

8           72
....

现在我需要能够将这些值输出到像这样的Excel电子表格中,

  

52 | 72 | 92 | 112 | 132

以下是我当前的代码,它允许我输出

  

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

a是模块访问数据库中的c.fetchall() 任何帮助表示赞赏

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()

2 个答案:

答案 0 :(得分:0)

您需要按如下方式更改查询:

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

这将返回您正在寻找的唯一值

答案 1 :(得分:0)

是否要从数据库列中删除重复项并将其存储在Excel中?如果是这样,那么下面的代码可以帮助你。

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)