0

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.

2 Answers 2

1

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")
0
0

You are indeed missing a bit there:

in your function sql_connect, you assign to a local variable named c.

That variable is not existant outside your function. If you want a connection variable to exist on module level, maybe try the following attempt:

In your "connect_to_db.py":

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()

cursor = sql_connect()

This creates a varibale "cursor" on the level of the module. In another module, simply perform

from connect_to_db import cursor

to import the module's "cursor" member.

This should do the trick.

Hint: Please be advised that this approach may not be very elegant, in terms of software-engineering.

Edit:

Maybe, you may want to dive deeper into object-oriented programming?

class MSSQLConnector(object):

    def __init__(self, server, port, database, user, password):
        self.server = server
        self.port = port
        self.conn = pyodbc.connect('DRIVER={SQL Server};SERVER='{0},
            {1}.format((self.server, self.port)), user, password, database)
    def open_cursor(self):
        return self.conn.cursor()

Which would be used in this fashion:

connector = MSSQLConnector("my_server", "1433", "my_database", "username", "secret-password")
cursor = connector.open_cursor()
3
  • Thanks, this works! In terms of elegance, would you recommend the approach of tomasmor? Or are there even nicer ways to build this?
    – edgar piet
    Feb 28, 2017 at 10:38
  • In terrms of elegance, @tomasmor provided a much cleaner solution. Having a cursor instantiated on module level is a bit "magic", which should, in general, be avoided. Also, have a look at resource guards in python, which will even facilitate closing and error-checking when resources go out of scope.
    – DrGlitch
    Feb 28, 2017 at 11:21
  • Thanks! I was afraid you were going to bring up object-oriented programming... I have been able to put my head in the sand for quite some time, but I think my time has come...
    – edgar piet
    Feb 28, 2017 at 12:27

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.