Insert data with Python script to a MSSQL server
Author: Maksim Merkulov
Categories:
scripting
This Python script can insert data in the database table remote server
Insert SQL - Github full source code
if __name__ == "__main__":
parser = createParser()
console_args = parser.parse_args(sys.argv[1:])
print(console_args)
conn = pyodbc.connect('DRIVER={SQL Server};SERVER=SERVER_NAME;DATABASE=DATABASE_NAME;TrustedConnection=yes;UID=User_ID;PWD=' + str(console_args.ps)+'')
cursor = conn.cursor()
# Read data from table
sql_query = pd.read_sql_query('SELECT * FROM DATABASE_NAME.db_owner.results_load', conn)
print(sql_query)
print(type(sql_query))
file_name = str(console_args.file) # change it to the name of your excel file
excel_dataframe = read_excel(file_name, sheet_name=0, header=0)
len_strings = len(excel_dataframe.index)
rand_value = generate_random()
now = datetime.datetime.now()
date_time_value = now.strftime("%Y-%m-%d %H:%M:%S")
i = 0
# test insert 1 element
print(bool(excel_dataframe.at[i, 'Stat']))
print(bool(re.search("TRUE", str(excel_dataframe.at[i, 'Stat']))))
# Write our information in a database
i = 0
# iterating over indexes
for col in excel_dataframe.index:
cursor.execute(
"INSERT INTO real_retentionpolicy.db_owner.results_load([id],[date],[path],[stat],[department]) values (?, ?, ?,?,?)",
rand_value, date_time_value, excel_dataframe.at[i, 'File link'],
correct_bool(excel_dataframe, i, 'Stat'),
sub_value_for_number(excel_dataframe, i, 'File link'))
i += 1
# END NEW LOAD
conn.commit()
conn.close()
Start the script from cmd
python sql_test.py -f input_file.xlsx -ps password -end 1
or
python sql_test.py --ps password --file input_file.xlsx