import sqlite3 as db
import fn

data_base = db.connect('data_stock')
data_base.row_factory = fn.dict_factory  # 强制输出字典格式
cursor = data_base.cursor()
table = 'stock_zxg'


# 插入数据库
def insert_row(data):
    stock_code = data.get('code')

    cursor.execute(
        "insert into '%s' (code) VALUES ('%s')" % (table,stock_code))
    data_base.commit()


# 删除数据库
def del_row(data):
    # 缓存期为一天
    stock_code = data.get('code')
    cursor.execute(
        "delete from '%s' where code = '%s'" % (table,stock_code))
    data_base.commit()


def save(data):
    stock_code = data.get('code')
    cursor.execute(
        "create table if not exists '%s' (id INTEGER PRIMARY KEY AUTOINCREMENT,code varchar(32),name varchar(32))" % (table))
    data_base.commit()

    cursor.execute("select id from %s where code = '%s'" % (table,stock_code))
    # 获得查询结果集:
    values = cursor.fetchone()

    if not values:
        insert_row(data)
        return 1
    else:
        del_row(data)
        return 0

# 插入数据库
def list():
    cursor.execute(
        "select code from '%s'" % (table))
    res = cursor.fetchall()
    return res