'Python/SQL how to append last line from a dataframe (or a dictionary) into SQL table
I created some code where I loop through and track my progress with a counter.
But when I try to append the current line I am in, into my sql table it fails, this feels like it should be the easiest part of this work but keeps failing.
Below is how I connect to the db and try to append the new line (dictionary) in:
quoted = urllib.parse.quote_plus("DRIVER={SQL Server};SERVER=myserver;DATABASE=mydb;Integrated Security=true;")
engine = sqlalchemy.create_engine('mssql+pyodbc:///?odbc_connect={}'.format(quoted))
new_line.to_sql('newtable', schema='schema', if_exists= "append" , con=engine, index=False)
This fails even though the line contains the same headers.
What did work is when I appended a dataframe by mistake, but that was wrong since I just wanted to add the last line.
df_output = df_output.append(new_line, ignore_index=True)
df_output.to_sql('newtable', schema='schema', if_exists= "append", con=engine, index=False)
So, since it accepted the dataframe I tried to take the last line of the dataframe which is appended from the new_line:
df_output.iloc[-1].to_sql('newtable', schema='schema', if_exists= "append", con=engine, index=False)
I have tried creating dataframes made out of the line alone but none of these have worked.
Solution 1:[1]
Really unclassy solution I found, but I created the dataframe right before adding the line, so I will only have one line. Then append it to the SQL table and it worked.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Daniel |
