You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python+SQLite3在线图书馆搜索功能异常及扩展需求技术咨询

Hey Hugo, let's work through your two library system issues step by step!

1. Fixing the "can't return to main menu after search" problem

Looking at your current search() function, the confusion comes from that extra break right after displaying search results. That line kicks you out of the search loop immediately after one query—if you want to let users run multiple searches without jumping back to the main menu first, that break is the culprit.

Here's the fixed version that lets users search as many times as they want until they type FIN to return to the main menu:

def search():
    try:
        with connection() as conn:
            cursor = conn.cursor()
            while True:
                recherche = input("Quel livre recherchez-vous ? Tapez 'FIN' pour retourner au menu : ")
                if recherche.upper() == 'FIN':
                    break  # Only exit when user explicitly types FIN
                # Add % before and after to support partial matches (e.g., "Potter" finds "Harry Potter")
                sql = "SELECT id_livre, titre_livre, auteur_livre FROM Livres WHERE titre_livre LIKE ?"
                cursor.execute(sql, (f'%{recherche}%',))
                lignes = cursor.fetchall()
                if not lignes:
                    print("Aucun livre trouvé !")
                else:
                    for ligne in lignes:
                        print(f"ID: {ligne[0]} | Titre: {ligne[1]} | Auteur: {ligne[2]}")
    except Exception as e:
        print(f'Erreur lors de la recherche : {e}')

Now, after each search, the loop will prompt the user again for a new query or FIN to head back to the main menu.

2. Adding author-based search functionality

To let users search by title or author (and show all books by that author), we'll add a quick selection step at the start of the search function. This lets users pick their search type before entering their query.

Here's the expanded search() function that supports both modes:

def search():
    try:
        with connection() as conn:
            cursor = conn.cursor()
            while True:
                # Show search mode options first
                print("\n=== Menu de Recherche ===")
                print("1. Rechercher par titre")
                print("2. Rechercher par auteur (afficher tous ses livres)")
                print("3. Retourner au menu principal")
                search_choice = input("Votre choix : ")

                if search_choice == "3":
                    break
                elif search_choice == "1":
                    titre = input("Entrez le titre (ou une partie) : ")
                    sql = "SELECT id_livre, titre_livre, auteur_livre FROM Livres WHERE titre_livre LIKE ? ORDER BY titre_livre"
                    cursor.execute(sql, (f'%{titre}%',))
                elif search_choice == "2":
                    auteur = input("Entrez le nom de l'auteur : ")
                    sql = "SELECT id_livre, titre_livre, auteur_livre FROM Livres WHERE auteur_livre LIKE ? ORDER BY titre_livre"
                    cursor.execute(sql, (f'%{auteur}%',))
                else:
                    print("Choix invalide, veuillez réessayer.")
                    continue  # Jump back to search option selection

                # Display formatted results
                lignes = cursor.fetchall()
                if not lignes:
                    print("Aucun résultat trouvé !")
                else:
                    print("\nRésultats :")
                    for ligne in lignes:
                        print(f"ID: {ligne[0]} | Titre: {ligne[1]} | Auteur: {ligne[2]}")
    except Exception as e:
        print(f'Erreur lors de la recherche : {e}')

Key improvements here:

  • Users can now choose between title and author search
  • Partial matches work for both (e.g., typing "Rowl" finds all J.K. Rowling books)
  • Results are sorted by title for better readability
  • Clear feedback when no results are found
  • An easy way to return to the main menu at any time

Quick extra fix for your code:

I noticed all your error messages say "while creating the table"—that's not accurate for delete/search operations. I updated the error messages in the code above to match the actual action (e.g., "Erreur lors de la recherche").


内容的提问来源于stack exchange,提问作者Hugo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.28 06:40:19