0

I have the following function that writes to SSMS, successfully, when I go in and change the table_name variable. But, I would like the name of whatever the df is being passed into the function to become the table name. E.g. if I am passing the df my_test_table into the function, I want the following SQL table to be named the same thing.


import urllib
import sqlalchemy

def write_to_sql(df):
    
    params = urllib.parse.quote_plus(r'DRIVER={};SERVER={};DATABASE={};Trusted_connection=yes;')

    conn_str = 'mssql+pyodbc:///?odbc_connect={}'.format(params)

    engine = sqlalchemy.create_engine(conn_str)

    table_name = #make this the same thing as the df name

    df.to_sql(name=table_name, con=engine, schema='yep', if_exists='replace', index=True, index_label=None, chunksize=10, dtype=None)   

write_to_sql(my_test_table) #want the table_name variable in the function to equal this

I have tried to use something like table_name = 'df'.format(df), but that didn't work, as it just forces the table_name to be df. What's the solution?

papelr
  • 468
  • 1
  • 11
  • 42
  • What exactly do you mean by df name? If you mean the variable name that you are passing to the function, there's not really a great way in python to do that – Jim Aug 11 '21 at 20:07
  • I mean df being whatever table I'm passing to the table. I was hoping there was a way to do it in python, without having to go in and change the `table_name` every time I write a table – papelr Aug 11 '21 at 20:10
  • This is more or less just trying to get the name of the variable passed to a function as a string within that function. It's really not good practice but there's a few very hacky examples here https://stackoverflow.com/questions/2749796/how-to-get-the-original-variable-name-of-variable-passed-to-a-function – Jim Aug 11 '21 at 20:14

0 Answers0