AttributeError:“module”对象没有属性“connection”

2024-09-28 23:26:17 发布

您现在位置:Python中文网/ 问答频道 /正文

我的代码开头是:

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

但我的错误是:

^{pr2}$

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


Tags: topathtextnametypeconnectioncardquery
3条回答

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

sqlite3.connection不存在。您要查找的函数名为^{}

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

另外,您不应该使用str.format或类似的工具将值插入到查询中。从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.)

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

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

  2. 在我的IDE上,sqlite3模块没有connection方法。。也许{}?

相关问题 更多 >