edgar piet edgar piet -4 years ago 114
Python Question

Connect to SQL server from self made module

I currently have many scripts that connect to the same MSSQL database. I make the connection in each of the scripts, but for ease of use I want to put the connection in a module and call that module from my script. The code in my module connect_to_db.pyc looks like this:

import pyodbc

def sql_connect():
server="some_server.net"
port="1433"
user = "my_username@my_domain"
server="my_server"
database="my_database"
conn = pyodbc.connect('DRIVER={SQL Server};SERVER=my_server,1433',
user=user,
password=password,
database=database)
c=conn.cursor()


Then, in my script I try to call this module and run a query:

from connect_to_db import sql_connect

sql_connect()
c.execute("SELECT * FROM table")


I get the error that the name c is not defined. I tried to define it as a global too, but it don't help. It must have something to do with my lack of understanding modules, but I can't figure out what.

Answer Source

You can return cursor in your sql_connect function

 import pyodbc

def sql_connect():
     server="some_server.net"
     port="1433"
     user = "my_username@my_domain"
     server="my_server"
     database="my_database"
     conn = pyodbc.connect('DRIVER={SQL Server};SERVER=my_server,1433', 
     user=user, 
     password=password, 
     database=database) 
     return conn.cursor()

And then you can use it as

from connect_to_db import sql_connect

c = sql_connect()
c.execute("SELECT * FROM table")
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download