import sqlite3
from sqlalchemy.types import NVARCHAR
def create_table(code):
    conn = sqlite3.connect(code + '.db')
    try:
        cursor = conn.cursor()
        
        table_name = "stock_data"
        cursor.execute(f'''CREATE TABLE IF NOT EXISTS {table_name} (
            日期 TEXT,
            开盘 REAL,
            收盘 REAL,
            最高 REAL,
            最低 REAL,
            成交量 INTEGER,
            成交额 REAL,
            振幅 REAL,
            涨跌幅 REAL,
            涨跌额 REAL,
            换手率 REAL
        )''')
    except sqlite3.Error as e:
        print(f"Database error: {e}")
    finally:
        conn.close()
        
        
def insert_data(code, data):
    conn = sqlite3.connect(code + '.db')
    try:
        cursor = conn.cursor()

        table_name = "stock_data"
        col_name_list = data.columns.tolist()
        # data.to_sql(table_name, conn, if_exists='append', index=False)
        data.to_sql(table_name, conn, if_exists='append',
                dtype={col_name: NVARCHAR(length=255) for col_name in col_name_list}, index=False)
        print("数据已成功插入到数据库中。")
        
        cursor.execute("SELECT * FROM stock_data LIMIT 2;")
        print(cursor.fetchall())
    except sqlite3.Error as e:
        print(f"插入数据时出错：{e}")
    finally:
        conn.close()