conn = sqlite3.connect(path+'\db.db') cur = conn.cursor()
cur.execute('create table if not exists numbers (id integer primary key ,number varchar(20) NOT NULL)') conn.commit()
i = 0 for file in files: if file.split('.')[-1] == 'txt': with open(file,'r',encoding = 'UTF-8') as f: next(f) for line in f: i += 1 print("插入第", i, "条数据:") #print(line) cur.execute('insert into numbers values(?,?)',(i,line)) conn.commit() cur.close() conn.close() print('数据写入完成!共写入',i,' 条数据')
cur.execute("SELECT * from numbers limit 0,50;") conn.commit data = cur.fetchall() print(data)
2.6 查询表中所有记录
# 5.查询表中所有记录 cur.execute("SELECT * from numbers;") data_all = cur.fetchall() a = len(data_all) print('共有 '+ str(a) + ' 条记录') #print(data)
2.7 查询表中不重复记录
cur.execute("SELECT distinct number from numbers;") data_distinct = cur.fetchall() b = len(data_distinct) print('共有 '+ str(b) +' 条不重复记录') #print(data_distinct)
2.8 将老表中的不重复记录插入新表
# 创建一个新表 cur.execute('create table if not exists numbers_distinct (id integer primary key ,number varchar(20) NOT NULL)') conn.commit() # 插入数据 i = 0 for data in data_distinct: i += 1 data = data[0] #print(data) cur.execute('insert into numbers_distinct values(?,?)',(i,data)) conn.commit()
2.9 将特定结果写入文本文件(单列)
cur.execute("SELECT number from numbers_distinct limit 0,10;") datas = cur.fetchall() #print(datas) with open('datafile1.txt','w') as f1: for data in datas: f1.write(data[0]) f1.flush()
cur.execute("SELECT * from numbers_distinct limit 0,10;") datas = cur.fetchall() #print(datas) with open('datafile2.txt','w') as f2: for data in datas: data0 = str(data[0]) # 将int类型转为str,否则write函数报错 data = data0 + ' ' + data[1] # 在两列之间以Tab键分隔 f2.write(data) f2.flush()
with open('datafile3.csv','w') as f3: for data in datas: data0 = str(data[0]) # 将int类型转为str,否则write函数报错 data = data0 + ',' + data[1] # 在两列之间以逗号键分隔 f3.write(data) # data是元组类型 f3.flush() # 重要!将缓冲区的数据写入文件中