-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathread_DB.py
More file actions
51 lines (40 loc) · 1.36 KB
/
read_DB.py
File metadata and controls
51 lines (40 loc) · 1.36 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
# -*- coding:utf-8 -*-
import sqlite3
# 创建表
def create_table(db_name, table_name):
conn = sqlite3.connect('%s.db' % db_name)
cursor = conn.cursor()
cursor.execute("create table %s (id INTEGER PRIMARY KEY AUTOINCREMENT,result text UNIQUE,date timestamp not null default (datetime('now','localtime')))"%table_name,)
cursor.close()
conn.close()
# 读取数据库
def read_db(db_name, table_name, size=100):
conn = sqlite3.connect('%s.db' % db_name)
cursor = conn.cursor()
cursor.execute('select * from ?', table_name)
result_all = cursor.fetchmany(size)
cursor.close()
conn.close()
return result_all
# 写入数据库
# 由于写入数据库比较耗时,直接将更新的所有传递给write_db
def write_db(db_name, table_name, result_list):
conn = sqlite3.connect('%s.db' % db_name)
cursor = conn.cursor()
new_list = []
for result in result_list:
sql = "insert into %s (result) values ('%s')" % (table_name, result)
#cursor.execute(sql)
#conn.commit()
try:
cursor.execute(sql)
new_list.append(result)
conn.commit()
print(u"写入 "+sql+u" 成功!")
except:
print(result+u" 已存在!")
cursor.close()
conn.close()
return new_list
if __name__ == '__main__':
create_table('test', 'test')