我正在使用DataGrip或SQLiteStudio (数据库管理器)在数据库中运行一系列查询,这些查询将引导我找到所需的信息。查询运行良好,结果显示在数据库管理器的控制台中。但是,我需要将数据库管理器控制台中显示的结果导出到一个CVS文件中。
我已经看到每个人都直接在shell中工作,但是我需要(我必须)使用DB管理器来运行查询(到目前为止,我需要在一个步骤中运行大约600行查询)。
在sqlite3外壳程序中,我能够运行(和工作) (.headers on) (.mode csv) (.output C:/filename.csv) (从"6000_1000_Results";) (select * from“6000_1000_Results”;) (.output标准输出)
但是,在数据库管理器的sql编辑器中运行此代码根本不起作用。
--(.....)
--(around 600 lines before)
--(.....)
"Material ID",
"Material Name",
SUM("Quantity of Material") Quantity
FROM
"6000_1000_Results_Temp"
GROUP BY
"DataCenterID", "Material ID";
------------------------------------------------------------
--(HERE IS WHERE I NEED TO EXPORT THE RESULTS IN A CVS FILE)
------------------------------------------------------------
.headers on
.mode csv
.output C:/NextCloudLuis/TemproDB.git/csvtest.csv
select * from "6000_1000_Results";
.output stdout
.show
DROP TABLE IF EXISTS "6000_1000_Results_Temp";
DROP TABLE IF EXISTS "6000_1000_Results";Datagrip不显示任何错误,它在几秒钟内运行查询,但没有任何文件,SQLiteStudio给出一个语法错误。
发布于 2019-08-20 16:28:25
最后,我将在接下来的步骤中解决这个问题:我使用lybrary sqlite3遍历python的所有查询。然后将所有查询的结果保存在pandas数据帧中。然后将pandas数据帧导出到cvs和xlxs文件。
以下是python代码:
import sqlite3
import queries
conn = sqlite3.connect("tempro.db") #make the database connection to python
level4000 = queries.level4000to1000(conn) #I call the function in queries.py
level4000.to_csv('Level4000to1000.csv') #export result ro cvs
level4000.to_excel('Level4000to1000.xlsx') #export result ro xlsx
conn.close() 下面是我保存所有查询的python文件(queries.py)
import sqlite3
from sqlite3 import Error
import pandas as pd
def level4000to1000(conn):
cur = conn.cursor()
cur.executescript(
"""
/* Here I put all the 600 lines of queries */
DROP TABLE IF EXISTS "4000_1000_Results_Temp";
DROP TABLE IF EXISTS "4000_1000_Results";
/* Here more and more lines */
--To keep the results from all queries
CREATE TABLE "4000_1000_Results_Temp" (
"DeviceID" INTEGER,
"Device Name" TEXT,
SUM("Quantity of Material") Quantity
FROM
"4000_1000_Results_Temp"
GROUP BY
"DeviceID", "Material ID";
""")
df = pd.read_sql_query('''SELECT * FROM "4000_1000_Results";''', conn)
cur.executescript("""DROP TABLE IF EXISTS "4000_1000_Results_Temp";
DROP TABLE IF EXISTS "4000_1000_Results";""")
return df #returns a dataframe with the info results from the queries最后,似乎没有办法使用SQL编码将结果导出为cvs格式的文件。
https://stackoverflow.com/questions/57391068
复制相似问题