import sqlite3#导入数据库 #连接到数据库,数据库文件是test.db。若文件不存在会自动在当前目录创建 conn=sqlite3.connect('test.db') cursor=conn.cursor()#创建一个cursor #print(cursor.execute('drop table user'))#删除user表 print(cursor.execute('create table user (id varchar(20) primary key, name varchar(20))'))#创建user表 print(cursor.execute('insert into user (id,name) values (\'1\',\'Michael\')'))#往表中插入一条记录 print(cursor.rowcount)#获得插入的行数 print(cursor.execute('select * from user where id=?', ('1',)))#查询表中记录 print(cursor.fetchall())#输出表中记录 conn.commit#提交事务 conn.close()#关闭Cursor conn.close()#关闭连接
#运行结果如下: <sqlite3.Cursor object at 0x0000027546A17BC0> <sqlite3.Cursor object at 0x0000027546A17BC0> 1 <sqlite3.Cursor object at 0x0000027546A17BC0> [('1', 'Michael')]
db_file = os.path.join(os.path.dirname(__file__), 'test.db') if os.path.isfile(db_file): os.remove(db_file)
# 初始数据: conn = sqlite3.connect(db_file) cursor = conn.cursor() #cursor.execute('drop table user') cursor.execute('create table user(id varchar(20) primary key, name varchar(20), score int)') cursor.execute(r"insert into user values ('A-001', 'Adam', 95)") cursor.execute(r"insert into user values ('A-002', 'Bart', 62)") cursor.execute(r"insert into user values ('A-003', 'Lisa', 78)") conn.commit()
defget_score_in(low, high): ' 返回指定分数区间的名字,按分数从低到高排序 ' cursor.execute('select name from user where score between ? and ? order by score',(low,high)) return [n[0] for n in cursor.fetchall()]
from tkinter.tix import Tree from sqlalchemy import Column,String,create_engine from sqlalchemy.orm import sessionmaker from sqlalchemy.ext.declarative import declarative_base