0

I'm trying to write a class in order to create an sqlite table since I have to create quite a few tables for this assignment.

This is how I tried to approach:

def connect_database(database_name):
    table_connect = lite.connect(database_name)
    print "connected successfully"
    return table_connect


def create_table(name_of_table, *argument_name, *argument_type):

    # create_user = user_table.cursor()
    # create_user.execute("Drop table if EXISTS  user_table")
    # create_user.execute('create table user_table(user_id INT, user_name VARCHAR )')
    # create_user.close()

    table_create = name_of_table.cursor()
    table_create.execute("drop table if exists name_of_table")
    table_create.execute('''
    create table name_of_table(
      argument_name  argument_type
      argument_name  name_of_table
    )
    ''')

    print "create table successfully"

    table_create.close()

example = connect_database('example.db')
create_table(example, water, FLOAT)

The problems I have is not being able to pass multiple argument_names, or pass argument_type in the method.

Also, the program returns unresolved reference for water and FLOAT.

Is there anyway that I can finish the method?

Thanks

3
  • Tip: to properly format code edit your question and use the {} button after selecting it Commented Jun 13, 2016 at 2:58
  • And your unresolved reference error doesn't mean anything with the code you've shown. You can read about making a minimal reproducible example for more information Commented Jun 13, 2016 at 2:59
  • you want to write a method that executes SQL commands? you're going to pass multiple arguments to the method but you can't? what are you going to do? Commented Jun 13, 2016 at 3:00

1 Answer 1

1

really you should probably consider using an ORM like sqlalchemy ... writing your own database abstraction, based on the your current skill level is probably a recipe for disaster, however if you really must try something like this

def create_table_string(table_name,*fields):
    return "CREATE TABLE {table_name} ({fields})".format(table_name=table_name,
                                                         fields=",".join(fields))

def create_table(cursor,name_of_table, *fields):
    sql = create_table_string(table_name,*fields)
    print "SQL:",sql
    cursor.executescript(sql)

db = sqlite3.connect(my_database)
create_table(db.cursor(),"a_table","Field1 INT","Field2 String","Field3 PRIMARY KEY INTEGER")
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.