简体   繁体   English

是否可以创建python sqlite3函数来创建通用表

[英]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. 我正在尝试创建一个Python程序,该程序记录特定时间段内的股票价格,然后为单个股票创建一个表,在该表中我可以记录给定时间的股票买入和卖出价格。

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. 但是,我不想为每个股票编写单独的表,我宁愿编写一个函数,该函数可以让我将变量作为表/列的名称,并在列表中包含一系列变量,然后可以运行该函数并从列表中创建5个表。

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 : 使用format构建SQL:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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