| | 151 | * [參考] [http://mailliststock.wordpress.com/2007/03/01/sqlite-examples-with-bash-perl-and-python/ SQLite examples with Bash, Perl and Python] (2007-03-01) |
| | 152 | * 環境: Debian 5.0.4 , amd64 核心 |
| | 153 | {{{ |
| | 154 | jazz@drbl:~$ lsb_release -a |
| | 155 | No LSB modules are available. |
| | 156 | Distributor ID: Debian |
| | 157 | Description: Debian GNU/Linux 5.0.4 (lenny) |
| | 158 | Release: 5.0.4 |
| | 159 | Codename: lenny |
| | 160 | jazz@drbl:~$ uname -a |
| | 161 | Linux drbl 2.6.26-lustre-amd64 #1 SMP Sun Jun 28 18:28:02 CST 2009 x86_64 GNU/Linux |
| | 162 | }}} |
| | 163 | * 相關套件: [http://packages.debian.org/sqlite3 sqlite3],[http://packages.debian.org/python-pysqlite2 python-pysqlite2] |
| | 164 | {{{ |
| | 165 | jazz@drbl:~$ sudo apt-get install python-pysqlite2 sqlite3 |
| | 166 | jazz@drbl:~$ dpkg -l | grep sqlite |
| | 167 | ii python-pysqlite2 2.4.1-1 Python interface to SQLite 3 |
| | 168 | ii sqlite3 3.5.9-6 A command line interface for SQLite 3 |
| | 169 | }}} |
| | 170 | * 使用範例程式建立 test.db |
| | 171 | {{{ |
| | 172 | jazz@drbl:~$ vi pythonsqlite.py |
| | 173 | jazz@drbl:~$ chmod a+x pythonsqlite.py |
| | 174 | jazz@drbl:~$ ./pythonsqlite.py |
| | 175 | jazz@drbl:~$ file test.db |
| | 176 | test.db: SQLite 3.x database |
| | 177 | jazz@drbl:~$ sqlite3 test.db "select * from n" |
| | 178 | 1|john|smith |
| | 179 | }}} |
| | 180 | {{{ |
| | 181 | #!python |
| | 182 | #!/usr/bin/python |
| | 183 | from pysqlite2 import dbapi2 as sqlite |
| | 184 | |
| | 185 | db = sqlite.connect('test.db') |
| | 186 | cur = db.cursor() |
| | 187 | cur.execute('CREATE TABLE n (id INTEGER PRIMARY KEY, f TEXT, l TEXT)') |
| | 188 | db.commit() |
| | 189 | cur.execute('INSERT INTO n (id, f, l) VALUES(NULL, "john", "smith")') |
| | 190 | db.commit() |
| | 191 | cur.execute('SELECT * FROM n') |
| | 192 | print cur.fetchall() |
| | 193 | }}} |