title: Executing different queries using mysql-python
body: <p>I'm working with a remote db for importing data to my Django proyect's db.</p>
  
  <p>With the help of  <code>MySQLdb</code> I've managed with ease to create an importing function like the following:</p>
  
  <pre><code>def connect_and_get_data(useful_string):
      CONNECTION = MySQLdb.connect(host=..., port=...,
                                   user=..., passwd=..., db=...,
                                   cursorclass=MySQLdb.cursors.DictCursor,
                                   charset = "utf8")
      cursor = CONNECTION.cursor()
      cursor.execute("SELECT ... FROM ... WHERE ... AND some_field=%s", (useful_string))
      result = cursor.fetchall()
      cursor.close()
  </code></pre>
  
  <p>Very happy with that, works as expected.</p>
  
  <p>But going on with the code, I've noticed that sometimes I'll need to connect to the db again, in order to execute other different queries.</p>
  
  <p>The first idea was quite logical, to me:
  for every query I'll need, define a function which calls <code>connect_and_get_data</code> with the given query as parameter... something like this:</p>
  
  <pre><code>def get_data_about_first_amazing_topic(useful_string):
      query = "SELECT ... FROM ... WHERE ... AND some_field=%s" %(useful_string)
      connect_and_get_data(query)
      ...
  
  def get_data_about_second_amazing_topic(other_useful_string):
      query = "SELECT ... FROM ... WHERE ... AND some_field=%s" %(other_useful_string)
      connect_and_get_data(query)
      ...
  </code></pre>
  
  <p>with this modifications to <code>connect_and_get_data</code>:</p>
  
  <pre><code>def connect_and_get_data(query):
      ...
      cursor.execute(query)
      ...
  </code></pre>
  
  <p>As you already might imagine, this solutions fails.</p>
  
  <p>Reading mluebke's answer to the question <a href="https://stackoverflow.com/questions/1413057/python-mysql-fetch-query">python mysql fetch query</a></p>
  
  <p><em>"You are passing arguments to the execute function, not doing python string substitution"</em></p>
  
  <p>I understood immediately where I was wrong; but I still feel that something is missing: I've tried different solutions, but I'm definitely unhappy with all of them.</p>
  
  <p>Is there a <em>"good"</em> way to encapsulate my <code>connect_and_get_data(query)</code> function, in order to serve me the way I want, or I'm totally in the wrong path with this?</p>
  
  <p>Which ones are considered <em>"best practices"</em> in this situation?</p>