Python, SQL, Django shell

If you are anything like me, you poor fool, then although you love the database abstraction layer in django there are times when noodling around in python you’d like to quickly poke a bit of sql at your django created databases, wouldn’t you? You naughty, naughty thing… a bit like this perhaps…

    >>>from sql import prompt
>>>prompt()
sql:show tables;
((‘auth_group’,),
(‘auth_group_permissions’,),
(‘auth_message’,),
(‘auth_permission’,),
(‘auth_user’,)….. etc

sql:select * from music_chord;
((1L, ‘A’, 0L, 0L),
(2L, ‘D’, 0L, 0L),
(3L, ‘E’, 0L, 0L),
(4L, ‘G’, 0L, 0L),
(5L, ‘B’, 0L, 0L),
(6L, ‘Am’, 0L, 0L),
(7L, ‘C’, 0L, 0L)……etc

sql:describe music_chord;
((‘id’, ‘int(11)’, ‘NO’, ‘PRI’, None, ‘auto_increment’),
(‘name’, ‘varchar(200)’, ‘NO’, ‘UNI’, ”, ”),)

sql:exit
bye!
>>># Phew! Back into python after a quick peek into the bowels of the database

Well, now you can… drop this in your site-packages folder as sql.py

import os
from django.core.management import setup_environ
import settings

from django.db import connection, backend
from pprint import pprint

def prompt():
while 1:
sql = raw_input(“sql:”).strip()
if sql == ‘exit’:
print “bye!”
break
pprint (execute(sql))

def execute( sql):
cursor = connection.cursor()
cursor.execute(sql)
results = cursor.fetchall()
return results

This entry was posted in Uncategorized and tagged . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>