将查询正确传递到mysql数据库

wlzqhblo  于 2023-08-02  发布在  Mysql
关注(0)|答案(1)|浏览(108)

我使用Python 3.8.10
我正在尝试更新MySQL数据库中的类别:

def update_categories(automaton, df, engine):
    logging.info("Starting category update process...")
    update_list = []
    start_time = time.time()

    # tqdm is used for showing progress bar
    for index, row in tqdm(df.iterrows(), total=df.shape[0]):
        matches = list(automaton.iter(row['prompt'].lower()))
        if matches:
            categories = json.loads(row['categories'])  # Convert string back to list
            for match in matches:
                _, (keyword, category) = match
                if category not in categories:
                    categories.append(category)  # Now you can append to the list
            update_list.append((json.dumps(row['categories']), row['id']))
            
    if update_list:
        try:
            with engine.connect() as conn:
                for data in update_list:
                    query = f"UPDATE prompts SET categories = '{data[0]}' WHERE id = {data[1]};"
                    conn.execute(query) # <--- HERE I GET THE ERROR
            logging.info("Updated categories successfully.")
        except SQLAlchemyError as e:
            logging.error(f"An error occurred: {e}")
            print(e)
            
    end_time = time.time()
    time_taken = end_time - start_time
    logging.info(f"Category update process completed. Time taken: {time_taken} seconds")

字符串
我得到以下错误:

ObjectNotExecutableError('Not an executable object: \'UPDATE prompts SET categories = \\\'"[\\\\"fashion\\\\", \\\\"Painting\\\\"]"\\\' WHERE id = 1;\'')


直接在我的数据库上执行此查询可以工作:
UPDATE prompts SET categories = "[\"fashion\", \"Painting\"]" WHERE id = 1;
我需要在我的python代码中将上述查询传递到我的数据库中。
如何正确传递我的值来更新我的数据库,有什么建议吗?
感谢您的回复!

628mspwn

628mspwn1#

我认为最好使用参数化查询,而不是直接将值格式化为查询字符串。在本例中,我将使用sqlalchemy中的text()函数来创建参数化查询。
像这样的东西

from sqlalchemy import text

if update_list:
    try:
        with engine.connect() as conn:
            for data in update_list:
                query = text("UPDATE prompts SET categories = :categories WHERE id = :id;")
                conn.execute(query, categories=data[0], id=data[1])
        logging.info("Updated categories successfully.")
    except SQLAlchemyError as e:
        logging.error(f"An error occurred: {e}")
        print(e)

字符串

相关问题