aman
aman

Reputation: 1

importing MySQL in django

I downloaded The SQL API from here http://www.djangoproject.com/r/python-mysql/ (the official site) the problem is I don't know how to import it in django. for example whrn I type this:

from django.shortcuts import render_to_response
import MySQLdb
....
...
..

I get the following error:

Traceback (most recent call last):
  File "<console>", line 1, in <module>
ImportError: No module named MySQLdb

where should I extract the files, and what do I have to change to make it work ?

Upvotes: 0

Views: 3888

Answers (2)

FirePower
FirePower

Reputation: 444

If you want to use mysql as database for django project you need:

  1. install mysql.connector (pip install mysql-connector)
  2. in settings.py setup default database for django project

    DATABASES = {
        'default': {
            'ENGINE': 'mysql.connector.django',
            'NAME': 'name of your schema in mysql',
            'USER': 'root',
            'PASSWORD': '12345678',
            'HOST': 'localhost',
            'PORT': '3306',
        }
    }
    
  3. Use commands like result = Something.objects.all() to query database (read django shell documentation for more info how to insert and take data from database Making queries)

If you just want to use mysql commands and data in django module, you use same system like in simple python:

  1. install mysql.connector (pip install mysql-connector)
  2. include it in module (import mysql.connector)
  3. create connection (conection= mysql.connector.connect(user='', host='', port='', password='')
  4. create instance for communication with database (myquery=conection.cursor())
  5. make your datatbase query (myquery.execute("select yourdata from data.table"))
  6. take results from myquery (for q in myquery: results += q)

Example:

import mysql.connector


conection= mysql.connector.connect(user='root', 
host='localhost', port='3306', password='12345678')
myquery=conection.cursor()
myquery.execute("select something from data.table")

for q in myquery:
    results += q

Upvotes: 1

mossplix
mossplix

Reputation: 3865

When you extract it , cd into where you extracted it and run the setup.py file python setup.py install

Upvotes: 3

Related Questions