AttributeError:'module'对象没有属性'connection'

时间:2014-12-12 01:30:47

标签: python sqlite attributeerror

我的代码的开头是:

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()

但我的错误是:

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'

我尝试更改.py名称和我的数据库名称,但没有任何工作。如果可以的话请帮忙。

3 个答案:

答案 0 :(得分:0)

sqlite3.connection不存在。您正在寻找的功能称为sqlite3.connect

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

此外,您绝不应使用str.format或类似工具将值插入查询中。来自docs

  

通常,您的SQL操作需要使用Python中的值   变量。您不应该使用Python的字符串汇编查询   因为这样做是不安全的;它使你的程序   容易受到SQL注入攻击(请参阅http://xkcd.com/327/)   什么可能出错的幽默例子。)

     

相反,请使用DB-API的参数替换。把?作为一个   占位符,无论您想要使用哪个值,然后提供元组   value作为游标execute()方法的第二个参数。   (其他数据库模块可能使用不同的占位符,例如%s或   :1。)

答案 1 :(得分:0)

sqlite3模块没有名为“connection”的属性,但它有一个名为connect的属性。你应该尝试'connection = sqlite3.connect('practice1.db')'

答案 2 :(得分:0)

我看到了几个可能的错误:

  1. 从文件路径,我猜你在窗口。好吧,您需要更改文件路径:C:\\Users\\Mrs Rose\\Desktop\\以避免被混淆为转义字符。

  2. 在我的IDE上,sqlite3模块没有方法connection ..也许connect

相关问题