简体   繁体   中英

Is it possible to create a python sqlite3 function to create generic tables

I'm trying to create a python program which logs stock prices over certain periods of time, then creates a table for the individual stock where I can record the buy price and sell price of the stock at given times.

However, I don't want to have to code individual tables for each stock, I'd rather code a function which lets me put variables as the table/column name, and have a series of variables in a list which i can then run the function and create 5 tables from a list for example.

So far I've gotten:

def create_tables(s,bp,sp,Time):
    sql_command = """
    CREATE TABLE """s"""( 
    Stock_number INTEGER PRIMARY KEY, 
    """bp""" INTEGER, 
    """sp""" INTEGER, 
    """Time""" VARCHAR(30));"""
    cursor.execute(sql_command)

I'm trying to execute this in a loop

for i in stock:
   create_tables(stock[x],buy[x],sell[x],time)
   x = x + 1

But it just doesn't work.

Build your SQL using format :

sql_command = """
CREATE TABLE {} ( 
  Stock_number INTEGER PRIMARY KEY, 
  {} INTEGER, 
  {} INTEGER, 
  {} VARCHAR(30));""".format(s,bp,sp,Time)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM