13.07.2015 Views

The wxPython tutorial

The wxPython tutorial

The wxPython tutorial

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Working with databaseshttp://www.zetcode.com/wxpython/databases/<strong>The</strong>re are two ways for creating a connection object. We can create aconnection to a database on the filesystem. We simply specify thepath to the filename. We can also create a database in memory. Thisis done with a special string ':memory:'.We launch a python interpreter. We will test our examples there.$ pythonPython 2.5.1c1 (release25-maint, Apr 6 2007, 22:02:36)[GCC 4.1.2 (Ubuntu 4.1.2-0ubuntu4)] on linux2Type "help", "copyright", "credits" or "license" for more information.>>>>>> import sqlite3 as lite>>> con = lite.connect('people')>>> cur = con.cursor()>>> cur.execute('select name from neighbours')>>> print cur.fetchall()[(u'sandy',), (u'jane',), (u'mark',), (u'steven',), (u'alice',), (u'tom',), (u'jack',),>>> cur.close()>>> con.close()First we import the sqlite3 module. <strong>The</strong>n we connect to our peopledatabase. <strong>The</strong> database file is in our current directory. To create acursor object, we call the cursor() method of the connection object.After that we call two cursor object methods. <strong>The</strong> execute() methodexecutes SQL commands. <strong>The</strong> fetchall() method retrieves all datathat we have selected. <strong>The</strong> kosher way to end our work is to closethe cursor and the connection object.Commiting changesSQLite library works with transactions. It is important to understandhow it works. According to the documentation, for every DMLstatement, SQLite opens up a transaction. We must commit ourchanges to apply them. For every DCL statement, SQLite librarycommits automatically the changes. We will demonstrate this in shortexamples.>>> cur.execute("update neighbours set age=29 where name='lucy'")>>> cur.execute("select age from neighbours where name='lucy'")>>> print cur.fetchone()(29,)>>> cur.close()>>> con.close()>>> (CTRL + D)$ sqlite3 peoplesqlite> select age from neighbours where name='lucy';187 de 12 27/04/2008 1:06

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!