如何使用UNION语句在python中合并两个SQLite表(当前显示“ ValueError:参数为不支持的类型”错误消息)

时间:2019-05-09 12:41:00

标签: python pandas sqlite

我对python和sqlite都还很陌生,所以请多多包涵,因为我的方法肯定很引导!我正在尝试使用python 3.6将多个csv文件追加到sqlite3数据库中的现有表。我编写的代码将单个csv文件组合到一个熊猫数据框中,然后我通过添加/合并/删除列以使其与sqlite数据框中的列匹配来对其进行清理。然后,它将新数据帧导出为csv文件。我已经设法将此新的csv文件添加到现有数据库中,并在数据库中创建了一个新表。我想做的是将新表中的数据添加到数据库中的现有表中,因此我尝试使用UNION语句,但是它返回以下错误“ ValueError:参数为不受支持的类型”。我知道当我查看在数据库中创建的新表时,某些列的类型为“ REAL”而不是文本(尽管在导出csv之前将它们全部转换为“ str”),而表中的所有列我想使用UNION键入“ TEXT”来联接在一起,因此我怀疑这是问题还是UNION语句本身,但是我不确定哪个也不知道如何解决。任何帮助是极大的赞赏!!

导入sqlite3 导入操作系统 将熊猫作为pd导入 将numpy导入为np

def add_CO2_files_to_database(文件=无):

# If a list of filepaths isn't specified, use every csv file in the same
# directory as the script
if files is None:

    # Get the current directory
    cwd = os.getcwd()

    #Add every csv file that starts with 'FD_' to a list
    files = [cwd+'\\'+f for f in os.listdir(cwd) if f.startswith('FD_')]

#Merge the csv files above into single pandas data frame and add a column 
for file in files:

    df = pd.concat([pd.read_csv(fp).assign(file_name=os.path.basename(fp).split('.')[0]) for fp in files])

    #Create a new column called 'FD_serial' from the 'file_name' column 
    #that consists of just the FD serial number
    df['FD_serial'] = df['file_name'].str[0:11]

    #Create another column that combines the 'Day', 'Month', and 'Year' 
    #columns into 1 column called 'date'
    df['date'] = df['Month'].map(str)+'-'+df['Day'].map(str)+'-'+df['Year'].map(str)  

    #Combine columns 'date' and 'Time' into a column called 'date_time'
    #then convert column to datetime format
    df['date_time'] = pd.to_datetime(df['date'] + ' '+ df['Time'])

    #Create new column called 'id' that combines the FD serial number 
    #'FD_serial' and the timestamp 'date_time' so each line of data has a 
    #unique identifier in the database
    df['id'] = df['FD_serial'].map(str) + '_' + df['date'].map(str) + '_' + df['Time'].map(str)

    #Add column 'location' and populate with 'NaN'
    df['location'] = np.nan

    #Delete unneccesary columns: 'Month', 'Day', 'Year', 'Time', 'date', 'file_name'
    df = df.drop(["Month", "Day", "Year", "Time", "date", "file_name", "Mode"], axis=1)

    #Rename columns to match the SQLite database conventions
    df = df.rename({'Flux':'CO2_flux', 'Temperature (C)':'temp', 'CO2 Soil (ppm) ':'soil_CO2', 'CO2 Soil STD (ppm)':'soil_STD',
               'CO2 ATM (ppm)':'atm_CO2', 'CO2 ATM STD (ppm)':'atm_std'}, axis='columns')

    #Change data types of all columns to 'str' so it matches the data type in the database
    df = df.astype(str)

    #Save the merged data frame in a csv file called 'FD_CO2_data.csv'
    df.to_csv("FD_CO2_data.csv", index=False)

下面的代码部分将CSV文件创建到数据库上方

#Connect to the SQLite Database and create a cursor   
conn = sqlite3.connect("email_TEST.db")
cur = conn.cursor()

#Read in the csv file 'FD_CO2_data.csv' that was created above
df = pd.read_csv('FD_CO2_data.csv')

#Add the csv file to the database as a new table
df.to_sql('FD_CO2', conn, if_exists='append', index=False)

#df_db = pd.read_sql_query("select * from FD_CO2 limit 5;", conn)
cur.execute("SELECT id, FD_serial, date_time, CO2_flux, temp, Soil_CO2, soil_STD, atm_CO2, atm_STD, location  FROM CO2 UNION SELECT id, FD_serial, date_time, CO2_flux, temp, Soil_CO2, soil_STD, atm_CO2, atm_STD, location FROM FD_CO2", conn)

print(df_db)

add_CO2_files_to_database()

1 个答案:

答案 0 :(得分:1)

将新表中的行插入到现有表中应该很容易

cur.execute("INSERT into CO2 select * from FD_CO2")

这假定FD_CO2中的列直接映射到CO2中的列,并且不会出现插入冲突,例如重复键。您将需要cur.commit()才能将行提交到数据库

UNION in sqlite是一个复合查询,它与数学上的并集本质上相同;它返回两个“集合”(即选择)的UNION。

错误"ValueError: parameters are of unsupported type"是由于conn的{​​{1}}参数引起的。参数化sql语句后,execute接受参数,即接受参数。 Here's the python doc on the subject.