Send SQL using python to a access database

Posted by Dark Training on October 15, 2007 tags: | python | sql

Example shown: the creation of a users Home folder and user information insertion into multiple databases

Python new user example:

import dbi #database independence utilities
import odbc #the ODBC module itself
from pprint import pprint #pretty-print function
full_name = raw_input("What is the Full name: ")
user = raw_input("What is the Username: ")
domain = 'domain\\'+user
email = user+"@some-email-domain.com"
myconn = odbc.odbc('DSN=database-name; PWD=databasepassword')
mycursor = myconn.cursor()
sql = "INSERT INTO Table_name( Code, Name, email, NT_name ) SELECT Max([Code]+1) AS Max_ID, '" + full_name + "', '" + email + "', '" + domain + "' FROM Dict_user"
mycursor.execute(sql)
myconn = odbc.odbc('DSN=database-name; PWD=databasepassword)
mycursor = myconn.cursor()
sql = "INSERT INTO Table_Name ( Code, Name, email, NT_name ) SELECT Max([Code]+1) AS Max_ID, '" + full_name + "', '" + email + "', '" + domain + "' FROM dict_Request"
mycursor.execute(sql)
import os
home_dir = 'H:\\'+user
os.mkdir(home_dir)

Ok so what is going on, first we open by importing our fuctions, in this case we need the ODBC module to talk to our database. pprint to format our ouput. Next we set our first variable, the new users full name. Now we set the users “Username” since in this example we assume that we use users u-name as part of the email address and also that the home folder is the user name. Now that we have the base information we create our first variable, the email address. In this case as mentioned above we are setting it to the “user” user name and the email domain. Next we need to open the ODBC connection to the database. In a windows enviroment you would have created the DSN previously by using the ODBC admin tool. In this example we set our DSN name “database-name” and the coresponding password “databasepassword”. Next using the cursor function we insert our SQL variable. This process is repeated below in the 2nd database. Last we make a new vairable that is the path to the users home folder. Note that for Python to draw a “" on screen you must enter it as “\” in your code, other wise Python will think you are tring to pass a command.