1

Using python, need to look into a dir and grab a filename, then insert the name into a MSSQL database with date/time for tracking purposes.

Web Results I keep coming across are for loading a whole CSV which we have in place and is already working for us. This need is just simply to pull the filename and add to a tracking table in MSSQL.

Here is the code that simply reads the files:

# read file
path = "Y:\\python\\working"
dirs = os.listdir( path )
# This prints all the files and directories (in our case it will be one file)
for file in dirs:
   print (file)

How can I take the result (filename) and insert filename and current date into a MSSQL DB with say a table name of "tracking" and two cols, file_name & date? There will be only 1 file at a time.

2
  • Possible duplicate of insert data into MSSQL server using python Commented Mar 28, 2019 at 19:42
  • @philshem that post is for adding the contents of a CSV to the DB. All I need to is to pull the filename as we already have the CSV loading processes in place. Commented Mar 28, 2019 at 19:56

1 Answer 1

2

assuming you have a table called tablename with a single char column called filename

import pyodbc
con_string='UID=%s;PWD=%s;DATABASE=%s;PORT=%s;TDS=%s;SERVER=%s;driver=%s' % (user,password, database,port,TDS_Version,server,driver)
....
cnxn=pyodbc.connect(con_string)
cursor=cnxn.cursor()
for f in dirs:
    cursor.execute("INSERT INTO tablename(filename) VALUES(?) ", (f))

cnxn.commit()
Sign up to request clarification or add additional context in comments.

3 Comments

@ philshem - this gets me to a point I can continue on, thank you.
For current date I added a col to MSSQL that auto adds date/time upon insert of the "filename".
Upvoted but the VALUES(?) practice I see all over the net is mystifying. There should be a way of simply inserting a string without the whole-dancing-around-the-issue. It will be a nightmare when I'm inserting a python list with thousands of entries.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.