title: Simplify database (psycopg2) usage by creating a module
body: <p>Let me preface this by saying that I am fairly new to Python and I apologize if this is not the appropriate place for this question.</p>
  
  <p>I am using the <strong>psycopg2</strong> module to manipulate a PostgreSQL database. The general usage would look something like this:</p>
  
  <pre><code># Example 1
  
  import psycopg2
  
  conn = psycopg2.connect(database="mydb", user="postgres")
  cur = conn.cursor()
  
  cur.execute ("SELECT * FROM mytable;")
  rows = cur.fetchall()
  for i, row in enumerate(rows):
      print "Row", i, "value = ", row
  
  cur.close()
  conn.close()
  </code></pre>
  
  <p>This will open a connection to the <strong>mydb</strong> database, select all fields from the table <strong>mytable</strong> and print them, and then close the connection.</p>
  
  <p>What I would like to do is factor out some of these functions into a module because I will need to call them over and over throughout many scripts. For this example, ideally I would have a module named <strong>core</strong> which contains three functions:</p>
  
  <ul>
  <li>core.db_init() - which opens the connection and consists of the first two lines of code above.</li>
  <li>core.db_query(query) - which performs the desired SQL query and consists of the third line in the above code.</li>
  <li>core.db_close() - which closes the connection and consists of the last two lines.</li>
  </ul>
  
  <p>I have tried creating a module as follows:</p>
  
  <pre><code># Module core.py
  
  import psycopg2
  
  def db_init():
      conn = psycopg2.connect(database="mydb", user="postgres")
      cur = conn.cursor()
  
  def db_query(query):
      cur.execute(query)
  
  def db_close():
      cur.close()
      conn.close()
  </code></pre>
  
  <p>But I get namespace errors when I try to recreate Example 1 using this module:</p>
  
  <pre><code># Example 2
  
  import core
  
  core.db_init()
  core.db_query("SELECT * FROM mytable;")
  
  rows = cur.fetchall()
  for i, row in enumerate(rows):
      print "Row", i, "value = ", row    
  
  core.db_close()
  </code></pre>
  
  <p>I'm not even sure a module is actually what I want. Should I be using a class instead? Again, I'm very new to all of this. But if someone could help me figure out a better way to do this, I would be very grateful.</p>