<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DZone Snippets: sqlobject code</title>
    <link>http://snippets.dzone.com/posts</link>
    <pubDate>Sat, 17 May 2008 14:35:39 GMT</pubDate>
    <description>DZone Snippets: sqlobject code</description>
    <item>
      <title>dbms database class</title>
      <link>http://snippets.dzone.com/posts/show/4242</link>
      <description>I'm at my first attempt at creating something for the PyS60 and I needed a simple sql wrapper class...&lt;br /&gt;I'm an experienced programmer, but has never programmed in python for s60 and it's been a while since I've used Python... So I hope this will help somebody, not annoy ;-)&lt;br /&gt;&lt;br /&gt;&lt;code&gt;&lt;br /&gt;# Filename: db.py save in your Python dir&lt;br /&gt;import e32db&lt;br /&gt;&lt;br /&gt;class db:&lt;br /&gt;    def __init__(self, dbpath):&lt;br /&gt;	self.db = e32db.Dbms()&lt;br /&gt;	self.dbv = e32db.Db_view()&lt;br /&gt;	self.reset_counters()&lt;br /&gt;	try:&lt;br /&gt;	    self.db.open(unicode(dbpath))&lt;br /&gt;	except:&lt;br /&gt;	    self.db.create(unicode(dbpath))&lt;br /&gt;	    self.db.open(unicode(dbpath))&lt;br /&gt;&lt;br /&gt;    def reset_counters(self):&lt;br /&gt;	self.affected_rows = 0&lt;br /&gt;	self.num_rows = 0&lt;br /&gt;	self.__internal_counter = 0&lt;br /&gt;&lt;br /&gt;    def query(self, sql):&lt;br /&gt;	self.reset_counters()&lt;br /&gt;	if sql.lower().startswith('select'):&lt;br /&gt;	    self.dbv.prepare(self.db, unicode(sql))&lt;br /&gt;	    self.dbv.first_line()&lt;br /&gt;	    self.num_rows = self.dbv.count_line()&lt;br /&gt;	else:&lt;br /&gt;	    self.affected_rows = self.db.execute(unicode(sql))&lt;br /&gt;&lt;br /&gt;    def next(self):&lt;br /&gt;	row = {'id': 0}&lt;br /&gt;	if self.num_rows &lt; 1:&lt;br /&gt;	    self.reset_counters()&lt;br /&gt;	    raise StopIteration&lt;br /&gt;	elif self.__internal_counter &lt; self.num_rows:&lt;br /&gt;	    self.dbv.get_line()&lt;br /&gt;	    for i in range(self.dbv.col_count()):&lt;br /&gt;		row[i] = self.dbv.col(i+1)&lt;br /&gt;	    self.dbv.next_line()&lt;br /&gt;	    self.__internal_counter += 1&lt;br /&gt;	    return row&lt;br /&gt;	else:&lt;br /&gt;	    self.reset_counters()&lt;br /&gt;	    raise StopIteration&lt;br /&gt;&lt;br /&gt;    def __iter__(self):&lt;br /&gt;	return self&lt;br /&gt;&lt;/code&gt;&lt;br /&gt;&lt;br /&gt;Now to create and fill db, create a file in the same dir as the db.py with this content:&lt;br /&gt;&lt;code&gt;&lt;br /&gt;# Change __exec_path to the path of your python script dir&lt;br /&gt;__exec_path = "E:\\Python\\"&lt;br /&gt;dbname = "test"&lt;br /&gt;&lt;br /&gt;import sys&lt;br /&gt;sys.path.append(__exec_path)&lt;br /&gt;from db import db&lt;br /&gt;&lt;br /&gt;# This will open E:\\Python\test.db - it will be created first, if not existing&lt;br /&gt;mydb = db(__exec_path+dbname+'.db')&lt;br /&gt;mydb.query("create table testing (id counter, name varchar)")&lt;br /&gt;mydb.query("insert into testing (name) values ('test 1')")&lt;br /&gt;mydb.query("insert into testing (name) values ('test 2')")&lt;br /&gt;&lt;/code&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;Now go ahead and have fun:&lt;br /&gt;&lt;code&gt;&lt;br /&gt;# Again change __exec_path to the path of your python script dir&lt;br /&gt;__exec_path = "E:\\Python\\"&lt;br /&gt;dbname = "test"&lt;br /&gt;&lt;br /&gt;import sys&lt;br /&gt;sys.path.append(__exec_path)&lt;br /&gt;from db import db&lt;br /&gt;&lt;br /&gt;# Opens E:\\Python\test.db&lt;br /&gt;mydb = db(__exec_path+dbname+'.db')&lt;br /&gt;mydb.query("select * from testing")&lt;br /&gt;for row in mydb:&lt;br /&gt;    print "-&gt; ",row[0]," ",row[1]," &lt;-"&lt;br /&gt;&lt;/code&gt;&lt;br /&gt;&lt;br /&gt;Have fun!&lt;br /&gt;Dan</description>
      <pubDate>Tue, 03 Jul 2007 21:46:51 GMT</pubDate>
      <guid>http://snippets.dzone.com/posts/show/4242</guid>
      <author>nerdcoder (Dan Larsen)</author>
    </item>
    <item>
      <title>ORM for pys60</title>
      <link>http://snippets.dzone.com/posts/show/1675</link>
      <description>I have asked for this a few months.&lt;br /&gt;Here's my own first version for an ORM.&lt;br /&gt;It's adapted from SQLAlchemy and SQLObject.&lt;br /&gt;(and whatever library I have searched)&lt;br /&gt;&lt;br /&gt;You need to create a database manually first.&lt;br /&gt;My previous snippets (&lt;a href=http://www.bigbold.com/snippets/posts/show/1669&gt;shell&lt;/a&gt;, &lt;a href=http://www.bigbold.com/snippets/posts/show/1668&gt;SQL&lt;/a&gt;) may help.&lt;br /&gt;&lt;code&gt;&lt;br /&gt;from __future__ import generators&lt;br /&gt;import e32db, re&lt;br /&gt;db = e32db.Dbms()&lt;br /&gt;dbv = e32db.Db_view()&lt;br /&gt;db.open(u'C:\\test.db')&lt;br /&gt;&lt;br /&gt;# Some helping classes (need more in next version)&lt;br /&gt;class String:&lt;br /&gt;    pass&lt;br /&gt;&lt;br /&gt;class Integer:&lt;br /&gt;    pass&lt;br /&gt;&lt;br /&gt;class Float:&lt;br /&gt;    pass&lt;br /&gt;&lt;br /&gt;class column:&lt;br /&gt;    def __init__(self, coltype):&lt;br /&gt;        self.coltype = coltype&lt;br /&gt;&lt;/code&gt;&lt;br /&gt;Here's the mother of all your classes that map to database tables.&lt;br /&gt;&lt;code&gt;&lt;br /&gt;class Mapper(object):&lt;br /&gt;    def __init__(self, id=None, **kw):&lt;br /&gt;        if id is None:&lt;br /&gt;            self.id = self._insert(**kw)&lt;br /&gt;        else:&lt;br /&gt;            self.id = id&lt;br /&gt;    def _insert(self, **kw):&lt;br /&gt;        names = ','.join(kw.keys())&lt;br /&gt;        values = ','.join([self.quote(k,v) for k,v in kw.items()])&lt;br /&gt;        tablename = self.__class__.__name__&lt;br /&gt;        q = u"INSERT INTO %s(%s) VALUES (%s)" % (tablename, names, values)&lt;br /&gt;        db.execute(q)&lt;br /&gt;        # get last insert ID&lt;br /&gt;        dbv.prepare(db, u'SELECT id FROM '+tablename+' ORDER BY id DESC')&lt;br /&gt;        dbv.first_line()&lt;br /&gt;        dbv.get_line()&lt;br /&gt;        return dbv.col(1)&lt;br /&gt;    def __getattr__(self, name):&lt;br /&gt;        if name in self.mapping.__dict__:&lt;br /&gt;            q = 'SELECT '+name+' FROM '+self.__class__.__name__&lt;br /&gt;            q += ' WHERE id='+str(self.id)&lt;br /&gt;            dbv.prepare(db, unicode(q))&lt;br /&gt;            dbv.first_line()&lt;br /&gt;            dbv.get_line()&lt;br /&gt;            return dbv.col(1)&lt;br /&gt;        else:&lt;br /&gt;            return self.__dict__[name]&lt;br /&gt;    def __repr__(self):&lt;br /&gt;        return '&lt;%s id=%d&gt;' % (self.__class__.__name__, self.id)&lt;br /&gt;    def quote(self, name, value):&lt;br /&gt;        if self.mapping.__dict__[name].coltype == String:&lt;br /&gt;            return "'%s'" % value.replace("'", "''")  # encode single quote&lt;br /&gt;        else:&lt;br /&gt;            return str(value)&lt;br /&gt;    def __setattr__(self, name, value):&lt;br /&gt;        if name in self.mapping.__dict__:&lt;br /&gt;            q = 'UPDATE '+self.__class__.__name__+' SET '+name+'='&lt;br /&gt;            q += self.quote(name, value) + " WHERE id=" + str(self.id)&lt;br /&gt;            db.execute(unicode(q))&lt;br /&gt;        else:&lt;br /&gt;            self.__dict__[name] = value&lt;br /&gt;    def set(self, **kw):&lt;br /&gt;        q = "UPDATE "+self.__class__.__name__+" SET "&lt;br /&gt;        for k, v in kw.items():&lt;br /&gt;            q += k+'='+self.quote(k,v)+','&lt;br /&gt;        q = q[:-1]+" WHERE id=%s" % self.id&lt;br /&gt;        db.execute(unicode(q))&lt;br /&gt;    def delete(self):&lt;br /&gt;        q = 'DELETE FROM '+self.__class__.__name__+" WHERE id=" + str(self.id)&lt;br /&gt;        db.execute(unicode(q))&lt;br /&gt;        self.id = None&lt;br /&gt;    def dict(self):&lt;br /&gt;        names = [k for k in self.mapping.__dict__.keys() if not k.startswith('__')]&lt;br /&gt;        q = 'SELECT '+','.join(names)+' FROM '+self.__class__.__name__&lt;br /&gt;        q += ' WHERE id=' + str(self.id)&lt;br /&gt;        dbv.prepare(db, unicode(q))&lt;br /&gt;        dbv.first_line()&lt;br /&gt;        dbv.get_line()&lt;br /&gt;        dct = {'id': self.id}&lt;br /&gt;        for i in range(dbv.col_count()):&lt;br /&gt;            dct[names[i]] = dbv.col(i+1)&lt;br /&gt;        return dct&lt;br /&gt;    def select(cls, where=None, orderby=None):&lt;br /&gt;        q = 'SELECT id FROM '+cls.__name__&lt;br /&gt;        if where:&lt;br /&gt;            q += ' WHERE '+where&lt;br /&gt;        if orderby:&lt;br /&gt;            q += ' ORDER BY '+orderby&lt;br /&gt;        dbv = e32db.Db_view()  # need its own cursor&lt;br /&gt;        dbv.prepare(db, unicode(q))&lt;br /&gt;        dbv.first_line()&lt;br /&gt;        for i in range(dbv.count_line()):&lt;br /&gt;            dbv.get_line()&lt;br /&gt;            yield cls(dbv.col(1))&lt;br /&gt;            dbv.next_line()&lt;br /&gt;    select = classmethod(select)&lt;br /&gt;&lt;/code&gt;&lt;br /&gt;Here's how you create your class.&lt;br /&gt;&lt;code&gt;&lt;br /&gt;class Person(Mapper):&lt;br /&gt;    class mapping:&lt;br /&gt;        # doesn't need id = column(Integer)&lt;br /&gt;        name = column(String)&lt;br /&gt;        age = column(Integer)&lt;br /&gt;&lt;/code&gt;&lt;br /&gt;</description>
      <pubDate>Fri, 10 Mar 2006 01:30:46 GMT</pubDate>
      <guid>http://snippets.dzone.com/posts/show/1675</guid>
      <author>korakot (Korakot Chaovavanich)</author>
    </item>
    <item>
      <title>Create an RSS feed from an SQL query</title>
      <link>http://snippets.dzone.com/posts/show/885</link>
      <description>&lt;code&gt;&lt;br /&gt;#!/usr/bin/env python&lt;br /&gt;# -*- encoding: latin1 -*-&lt;br /&gt;&lt;br /&gt;import datetime,PyRSS2Gen,sqlobject&lt;br /&gt;from sqlobject.postgres import builder&lt;br /&gt;&lt;br /&gt;con = builder()(user = 'user', passwd = '', host = 'localhost', db='name')&lt;br /&gt;&lt;br /&gt;# set db encoding (maybe optional)&lt;br /&gt;con.queryOne("SET client_encoding TO 'latin1'; SELECT 1;")&lt;br /&gt;&lt;br /&gt;items = []&lt;br /&gt;for res in con.queryAll("""SELECT title,url,datum,description FROM table ORDER BY datum DESC LIMIT 30"""):&lt;br /&gt;    items.append(&lt;br /&gt;        PyRSS2Gen.RSSItem(&lt;br /&gt;        title = res[0], link = res[1],&lt;br /&gt;        description = """&lt;h2&gt;%s&lt;/h2&gt;on %s&lt;br/&gt;&lt;p&gt;%s&lt;/p&gt;"""%(res[0],res[2],res[]3),&lt;br /&gt;        guid = PyRSS2Gen.Guid(res[1]), pubDate = res[2]))&lt;br /&gt;&lt;br /&gt;    # generate rss feed&lt;br /&gt;PyRSS2Gen.RSS2(&lt;br /&gt;    title         = "sql2rss feed",&lt;br /&gt;    link          = "http://localhost/die URL",&lt;br /&gt;    description   = "The latest sql2rss news",&lt;br /&gt;    lastBuildDate = datetime.datetime.now(),&lt;br /&gt;    items         = items).write_xml(open("sql2rss.xml", "w"))&lt;br /&gt;&lt;/code&gt;</description>
      <pubDate>Sun, 13 Nov 2005 02:51:47 GMT</pubDate>
      <guid>http://snippets.dzone.com/posts/show/885</guid>
      <author>tsch ()</author>
    </item>
    <item>
      <title>Declarative metaclass</title>
      <link>http://snippets.dzone.com/posts/show/779</link>
      <description>Metaclass is like a black magic in python.&lt;br /&gt;I wouldn't learn it if not necessary to read someone's code.&lt;br /&gt;SqlObject uses it. So, if I want to port it to pys60 Dbms,&lt;br /&gt;I need to learn metaclass.&lt;br /&gt;&lt;br /&gt;Fortunately, this one is not too much to understand.&lt;br /&gt;&lt;code&gt;&lt;br /&gt;class DeclarativeMeta(type):&lt;br /&gt;    def __new__(meta, class_name, bases, new_attrs):&lt;br /&gt;        cls = type.__new__(meta, class_name, bases, new_attrs)&lt;br /&gt;        if new_attrs.has_key('__classinit__'):&lt;br /&gt;            cls.__classinit__ = staticmethod(cls.__classinit__.im_func)&lt;br /&gt;        cls.__classinit__(cls, new_attrs)&lt;br /&gt;        return cls&lt;br /&gt;&lt;/code&gt;&lt;br /&gt;When you use it you do this&lt;br /&gt;&lt;code&gt;&lt;br /&gt;class YourClass(object):&lt;br /&gt;    __metaclass__ = DeclarativeMeta&lt;br /&gt;    # ... and other class variables&lt;br /&gt;    def __classinit__(cls, new_attrs):&lt;br /&gt;        # do whatever you want with the new class&lt;br /&gt;        # ...&lt;br /&gt;    def __init__(self):&lt;br /&gt;        # do whatever you want with the new instance&lt;br /&gt;&lt;/code&gt;&lt;br /&gt;You use this when you want a subclass to have some magic&lt;br /&gt;done to it when it is first defined. What you say in&lt;br /&gt;__classinit__ will get done to the new subclass, eg.&lt;br /&gt;create more methods, properties, etc.</description>
      <pubDate>Sat, 01 Oct 2005 19:23:44 GMT</pubDate>
      <guid>http://snippets.dzone.com/posts/show/779</guid>
      <author>korakot (Korakot Chaovavanich)</author>
    </item>
  </channel>
</rss>
