在很多小的应用开发中对数据的管理完全没必要让Mysql之类的大神级数据库登场,直接使用python自带的SQLite就已经足够了.
(我就要小轻快,能快速落地实用,可不想动不动就安装个数据库服务器之类的,忒麻烦.)
1.先测试一下python对SQLite操作是否好用
1)pycharm下建个项目test-SQLite,建个文件test_sqlitedb.py代码如下:
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
' a test sqlite '
__author__ = 'TianJiang Gui'
import sqlite3
conn = sqlite3.connect('sqlite-data.db')
cursor = conn.cursor()
cursor.execute('create table userinfo (id int(11) primary key, name varchar(20), age int)')
cursor.execute('insert into userinfo (id, name, age) values (1, \'gtj\', 45)')
print(cursor.rowcount)
cursor.execute('select * from userinfo where id=?', (1,))
values = cursor.fetchall()
print(values)
cursor.close()
conn.close()
过程很轻松,结果很完美:
但是别高兴的太早了,打开Navicate for SQLite 再看看是否真的有数据:
怎么会没有数据呢?在此重要的问题说三遍:在执行了增,删,改后一定要记得执行
conn.commit()
2.最终正确的代码在此:
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
' a test sqlite '
__author__ = 'TianJiang Gui'
import sqlite3
conn = sqlite3.connect('sqlite-data.db')
cursor = conn.cursor()
cursor.execute('create table userinfo (id int(11) primary key, name varchar(20), age int)')
cursor.execute('insert into userinfo (id, name, age) values (1, \'gtj\', 45)')
print(cursor.rowcount)
# ---gtj 一定记得执行commit
conn.commit()
cursor.execute('select * from userinfo where id=?', (1,))
values = cursor.fetchall()
print(values)
cursor.close()
conn.close()
再次通过Navicate for SQLite查看
现在才真的有数据了.
总结:python+sqlite真是完美的小应用开发组合,随后我就将对mysql的操作改造为对sqlite的操作,这样也便于我打包生成应用程序