SQLite,是一款轻型的数据库,占用资源非常低,支持Windows/Linux/Unix等等主流的操作系统,零配置 – 无需安装和管理配置,支持多种开发语言,C, C++, PHP, Perl, Java, C#,Python, Ruby等,SQLite虽然轻便小巧,但是支持大部分的SQL语句。
最近再写2048游戏的程序时,有人提示可以将玩游戏的最高分存入到数据库,这样以后每次进入游戏时可从数据库读取历史最高分记录展示出来。之前在其他的程序中使用过mysql数据库,觉得操作起来稍麻烦,这次试用了下sqlite,简直发现了新大陆,真的是很简单易操作,不管是创建连接数据库,还是操作数据都so easy。
1.创建并连接数据库,无需安装,无需安装,无需安装,两行代码搞定
import sqlite3
#连接数据库,有则直接连接,无则创建一个数据库
conn = sqlite3.connect('2048.db')
print ("Opened database successfully")
创建成功后,在项目目录下就自动生成了一个2048.db的文件。想查看该数据库的话,可使用navicat选择连接sqlite数据库查看。
2.创建表,如果表不存在则创建表
def create_table():
try:
create_tb_cmd='''
CREATE TABLE IF NOT EXISTS HighScore
(ID INT PRIMARY KEY NOT NULL,
SCORE INT DEFAULT 0,
REMARK CHAR(50));
'''
conn.execute(create_tb_cmd)
print('Create table success')
except:
print ("Create table failed")
return False
conn.commit()
3.插入数据
conn.execute("INSERT INTO HighScore (ID,SCORE,REMARK) VALUES (1, 100, '')")
conn.commit()
print ("Records created successfully")
4.查询数据
score=conn.execute("select SCORE from HighScore")
for score in score:
print (score[0])
5.更新数据
score=99
conn.execute("update HighScore set SCORE ={0} where ID=1".format(score))
conn.commit()
print('update success')
conn.close()
全部代码如下:
#-*-coding:utf-8-*-
import sqlite3
def create_table():#创建表
try:
create_tb_cmd='''
CREATE TABLE IF NOT EXISTS HighScore
(ID INT PRIMARY KEY NOT NULL,
SCORE INT DEFAULT 0,
REMARK CHAR(50));
'''
conn.execute(create_tb_cmd)
print('Create table success')
except:
print ("Create table failed")
return False
conn.commit()
#连接数据库,有则直接连接,无则创建一个数据库
conn = sqlite3.connect('2048.db')
print ("Opened database successfully")
#插入数据
conn.execute("INSERT INTO HighScore (ID,SCORE,REMARK) VALUES (1, 100, '')")
conn.commit()
print ("Records created successfully")
#查询数据
score=conn.execute("select SCORE from HighScore")
for score in score:
print (score[0])
#更新数据
score=99
conn.execute("update HighScore set SCORE ={0} where ID=1".format(score))
conn.commit()
print('update success')
conn.close()