Ask Your Question
3

How to add new SQL Server records and modify existing records in pandas dataframe?

asked 2021-12-27 11:00:00 +0000

plato gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
2

answered 2022-01-13 05:00:00 +0000

woof gravatar image

To add new records to a pandas dataframe that represents a SQL Server table, you can use the append() method combined with a new row of data. For example:

import pandas as pd
import pyodbc

# Connect to SQL Server
conn = pyodbc.connect('Driver={SQL Server};'
                   'Server=server_name;'
                   'Database=database_name;'
                   'Trusted_Connection=yes;')

# Load the data from the SQL Server table
df = pd.read_sql('SELECT * FROM table_name', conn)

# Append a new row of data to the dataframe
new_row = {'column1': 'value1', 'column2': 'value2', 'column3': 'value3'}
df = df.append(new_row, ignore_index=True)

# Modify an existing record in the dataframe
df.loc[df['column1'] == 'old_value', 'column1'] = 'new_value'

# Write the updated dataframe back to the SQL Server table
df.to_sql('table_name', conn, if_exists='replace', index=False)

In this example, we first connect to the SQL Server database using pyodbc. Then, we use pandas to load the data from the SQL Server table into a dataframe. Next, we append a new row of data to the dataframe using a dictionary with key-value pairs that map to the column names and values. We also set the ignore_index parameter to True to make sure that the new row is appended to the end of the dataframe with a new index value.

To modify an existing record in the dataframe, we use the loc[] method to select the row(s) we want to modify based on a condition, and then specify the column(s) we want to modify and the new value(s) we want to set.

Finally, we write the updated dataframe back to the SQL Server table using the to_sql() method, which takes the name of the SQL Server table as an argument, along with the database connection object, and the if_exists parameter set to 'replace' to overwrite the existing table with the updated data.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2021-12-27 11:00:00 +0000

Seen: 9 times

Last updated: Jan 13 '22