I am new to QGIS python development and I have a requirement to query the database and depending on the result do some processing in QGIS.

I found how to create a connection to mysql db on python cook book, but I was unable to execute a user defined query using a python plugin. I did search but am couldn't find any good article about that. Can anyone please help to find out how to execute user defined query inside a python plugin?


I would use string formatting. This example uses the MySQLdb module.

import MySQLdb

db = MySQLdb.connect(host="servername", user="username", passwd="yourpw", db="dbname") 
cur = db.cursor() 
cur.execute("SELECT %s FROM table WHERE something = '%s'") % (userdefined, userdefined_two)
for row in cur.fetchall():
    print row[0]

In the plugin you just need to get the users input and assign it to a variable, 'userdefined' and 'userdefined_two' in my example. e.g...

userdefined = self.dlg.ui.lineEdit.text()
  • Hi Matt, Thanks for the great help. NOw i am facing another problem, Do you know how to install MySQLdb in QGIS. When i tried to import it it says "ImportError: No module named MySQLdb" – keth Jan 22 '14 at 15:58
  • Hi Keth, You don't necessarily need to use the MySQLdb module, you mentioned you had created a connection to a MySQL database so you can just use the adapter you already have. However, you are getting that error because you do not have the module installed. Are you using windows or linux? – Matt Jan 23 '14 at 8:35
  • Hi Matt, i am using windows 7. How ever i was able to solve problem using following scenario. 1) downloaded MySQL-python-1.2.3.win32-py2.7.msi and installed. 2) from that installation i copied MySQLdb folder and other related files to QGIS Dufour\apps\Python27\Lib fiolder. Then i my plugn ran without any problem and i was able to access the database without any issue. Can you please explain how to use the existing connection inside the python plugin? Appreciate your help – keth Jan 23 '14 at 8:59
  • Hi Keth, excuse me for the late comment but u could give more details about how u performed the MySQLdb installation ? – snaileater May 22 '15 at 9:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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