Search code examples
pythonsqliteattributeerror

AttributeError: 'module' object has no attribute 'connection'


The beginning of my code is:

import sqlite3

def construct_query(card_name, card_type,card_type_whole, power, tough, card_text, exp,rare):

    query = "INSERT INTO CardComponet (all column names) VALUES ('{}','{}',{},{},'{}','{}','{}')".format(card_name, card_type_whole, power, tough, card_text, exp,rare)
    return query

path_to_flat_file = 'C:\Users\Mrs Rose\Desktop\inputf.txt'

flat_file_object  = open(path_to_flat_file, 'r')

connection = sqlite3.connection('practice1.db')

cursor  = connection.cursor()

But my error is:

Traceback (most recent call last):
  File "C:\Users\Mrs rose\Desktop\FinalProject.py", line 11, in <module>
    connection = sqlite3.connection('practice1.db')
AttributeError: 'module' object has no attribute 'connection'

I tried changing my .py name and my my database name but nothing is working. Please help if you can.


Solution

  • sqlite3.connection does not exist. The function you are looking for is called sqlite3.connect:

    >>> import sqlite3
    >>> sqlite3.connect
    <built-in function connect>
    >>>
    

    Also, you should never use str.format or similar tools to insert values into a query. From the docs:

    Usually your SQL operations will need to use values from Python variables. You shouldn’t assemble your query using Python’s string operations because doing so is insecure; it makes your program vulnerable to an SQL injection attack (see http://xkcd.com/327/ for humorous example of what can go wrong).

    Instead, use the DB-API's parameter substitution. Put ? as a placeholder wherever you want to use a value, and then provide a tuple of values as the second argument to the cursor's execute() method. (Other database modules may use a different placeholder, such as %s or :1.)