【问题标题】:Search for a table in MySQL Database via Python通过 Python 在 MySQL 数据库中搜索表
【发布时间】:2020-11-02 07:18:42
【问题描述】:

我正在编写一个脚本,该脚本在 python

中使用 mysql.connector 在数据库中创建一个表

我已经创建了函数

def create_table(connection):
    try:
        tb = 'D' + str(datetime.date.today())
        table_name = tb[:5] + tb[6:8] + tb[9:]

        if not find_table(connection, table_name):

            mySql_Create_Table_Query = """CREATE TABLE """ + table_name + """ (
                                        Id int(11) NOT NULL,
                                        Name varchar(3) NOT NULL,
                                        Date_check int(32) NOT NULL,
                                        Price float NOT NULL,
                                        PRIMARY KEY (Id)) """

            cursor = connection.cursor()
            result = cursor.execute(mySql_Create_Table_Query)
            print("Table created successfully ")
            cursor.reset()

        else:
            return

    except mysql.connector.Error as error:
        print("Failed to create table in MySQL: {}".format(error))
        if not connection.is_connected():
            print("You're not connected to a database")

接收connection 对象作为输入(在我的情况下,它由另一个名为connect() 的函数返回),然后,给定当前日期,它生成表名,然后生成实际表。

除了if not find_table(connection, table_name)之外一切正常

函数find_table(connection, table _ame)以字符串形式接收连接对象和表名作为输入,并执行如下研究:

def find_table(connection, table_name):
    try:

        mySql_Find_Table_Query = """SELECT COUNT(*)
                                    FROM information_schema.tables 
                                    WHERE table_schema = 'thegrkle_trading' 
                                    AND table_name = '""" + table_name + """'; """

        cursor = connection.cursor()
        result = cursor.execute(mySql_Find_Table_Query)
        print(result)

        if str(result) == 'None':
            print("The table does not exist ")
            cursor.reset()
            return False
        else:
            print("The table already exist ")
            cursor.reset()
            return True

    except mysql.connector.Error as error:
        print("Failed to find table in MySQL: {}".format(error))
        if not connection.is_connected():
            print("You're not connected to a database")

出于某种原因,即使我的数据库中存在该表,find_table 函数也会返回False

我尝试通过 PHPMyAdmin 将 SQL 查询 mySql_Find_Table_Query 直接运行到数据库中,并且运行良好。我无法理解,因为我的函数总是返回该表不存在

【问题讨论】:

  • Count(*) 在所有情况下都会返回一个数字。如果没有找到表,它将为 0。此外,如果不存在,编写 create tabke 会简单得多...
  • @Shadow 问题是execute() 总是返回None

标签: python mysql sql


【解决方案1】:

问题是如果查询执行正确,cursor.execute(mySql_Find_Table_Query) 总是返回 None

解决方案是使用fetchone() 并检查元组的值

cursor.execute(mySql_Find_Table_Query)
        result = cursor.fetchone()

        if result[0] == 0:
            print("The table does not exist ")
            cursor.reset()
            return False
        else:
            print("The table already exist ")
            cursor.reset()
            return True

【讨论】:

    猜你喜欢
    • 2011-12-02
    • 1970-01-01
    • 2021-10-28
    • 1970-01-01
    • 1970-01-01
    • 2021-10-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多