我正在尝试使用MySQLdb库连接到MySQL数据库。我收到一条错误消息,该函数没有游标属性。
我试着逐行运行连接代码,但没有将其包装在解释器的函数中,它可以正常工作。
import MySQLdb
import databaseconfig as dcfg
# databaseconfig.py contains the database credentials
# It is a config file and has no code
def mysqlconnect():
# Trying to connect
db_connection = None
try:
db_connection = MySQLdb.connect
(
dcfg.mysql["host"],
dcfg.mysql["user"],
dcfg.mysql["password"],
dcfg.mysql["db"],
dcfg.mysql["port"]
)
# If connection is not successful
except:
print("Can't connect to database")
return 0
# If Connection Is Successful
print("Connected")
# Making Cursor Object For Query Execution
cursor = db_connection.cursor()
# Function Call For Connecting To Our Database
mysqlconnect()预期的输出是生成一个游标。实际输出为:
Connected
Traceback (most recent call last):
File "models.py", line 43, in <module>
mysqlconnect()
File "models.py", line 26, in mysqlconnect
cursor = db_connection.cursor()
AttributeError: 'function' object has no attribute 'cursor'发布于 2019-10-16 04:12:38
这是由于您的语法所致。您的mysqlconnect函数应该如下所示:
def mysqlconnect():
# Trying to connect
db_connection = None
try:
db_connection = MySQLdb.connect(
dcfg.mysql["host"],
dcfg.mysql["user"],
dcfg.mysql["password"],
dcfg.mysql["db"],
dcfg.mysql["port"]
)
# If connection is not successful
except:
print("Can't connect to database")
return 0
# If Connection Is Successful
print("Connected")
# Making Cursor Object For Query Execution
cursor = db_connection.cursor()https://stackoverflow.com/questions/58401677
复制相似问题