首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >连接数据库时如何解析"AttributeError:'function‘object has no attribute 'cursor'“?

问连接数据库时如何解析"AttributeError:'function‘object has no attribute 'cursor'“?
EN

Stack Overflow用户
提问于 2019-10-16 03:45:09
回答 1查看 3.7K关注 0票数 0

我正在尝试使用MySQLdb库连接到MySQL数据库。我收到一条错误消息,该函数没有游标属性。

我试着逐行运行连接代码,但没有将其包装在解释器的函数中,它可以正常工作。

代码语言:javascript
复制
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()

预期的输出是生成一个游标。实际输出为:

代码语言:javascript
复制
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'
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-10-16 04:12:38

这是由于您的语法所致。您的mysqlconnect函数应该如下所示:

代码语言:javascript
复制
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()
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/58401677

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档