1

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.

2
  • Why don't you use one table and make the stock a column in this table? Commented Nov 2, 2016 at 12:52
  • To concatenate strings (add them together), use the + operator: "hello" + x + "world" Commented Nov 2, 2016 at 12:59

1 Answer 1

2

Build your SQL using format:

sql_command = """
CREATE TABLE {} ( 
  Stock_number INTEGER PRIMARY KEY, 
  {} INTEGER, 
  {} INTEGER, 
  {} VARCHAR(30));""".format(s,bp,sp,Time)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.