How can I connect MYSQL database in python for QGIS desktop Application?

المشرف العام

Administrator
طاقم الإدارة
I am following below process.

1 - Setting

You must install a MySQL driver before doing anything. Unlike PHP, only the SQLite driver is installed by default with Python. The most used package to do so is MySQLdb but it's hard to install it using easy_install.For Windows user, you can get an exe of MySQLdb.

2 - Usage

After installing, reboot. This is not mandatory, but will prevent me from answering 3 or 4 other questions in this post if something goes wrong. So please reboot.

Then it is just like using another package :

!/usr/bin/python

import MySQLdb

db = MySQLdb.connect(host="localhost", # your host, usually localhost user="john", # your username passwd="megajonhy", # your password db="jonhydb") # name of the data base

you must create a Cursor object. It will let

you execute all the queries you need

cur = db.cursor()

Use all the SQL you like

cur.execute("SELECT * FROM YOUR_TABLE_NAME")

print all the first cell of all the rows

for row in cur.fetchall() : print row[0]

Of course, there are thousand of possibilities and options; this is a very basic example. You will have to look at the documentation. A good starting point.

But it will give me error :

Couldn't load plugin Importtool due to an error when calling its classFactory() methodTraceback (most recent call last):

File "C:/PROGRA~1/QGISWI~1/apps/qgis/./python\qgis\utils.py", line 219, in startPlugin plugins[packageName] = package.classFactory(iface)

File "C:/Users/n/.qgis2/python/plugins\Importtool__init__.py", line 34, in classFactory from .Import_tool import Importtool

File "C:/PROGRA~1/QGISWI~1/apps/qgis/./python\qgis\utils.py", line 478, in _import mod = _builtin_import(name, globals, locals, fromlist, level)

File "C:/Users/n/.qgis2/python/plugins\Importtool\Import_tool.py", line 36, in import MySQLdb

File "C:/PROGRA~1/QGISWI~1/apps/qgis/./python\qgis\utils.py", line 478, in _import mod = _builtin_import(name, globals, locals, fromlist, level)

ImportError: No module named MySQLdb



أكثر...
 
أعلى