Database Creation - C# Programming Exercise

In this exercise, you need to create a program that asks the user for information about books (title, author, genre, and summary) and stores this data in an SQLite database. The goal of this exercise is to learn how to interact with databases using SQLite in C#, a lightweight and easy-to-use database management system. This exercise will allow you to create a database to store book information in a structured and efficient way. The book data, such as title, author, genre, and summary, will be entered by the user and saved in a table in the SQLite database.

By implementing this program, you will learn how to perform SQL queries in SQLite to store and retrieve information, how to connect your C# application with a database, and how to handle user input properly. Additionally, this exercise will help you understand the basics of database management, a key aspect of developing applications that manage persistent data.

 Category

Access To Relational Databases

 Exercise

Database Creation

 Objective

Create a program to ask the user for data about books (title, author, genre, and summary) and store them in a SQLite database.

 Write Your C# Exercise

// Importing necessary namespaces for SQLite operations, user input, and basic functionalities
using System; // For basic functionalities like Console and Exception handling
using System.Data.SQLite; // For SQLite operations

// Define the Book class to represent a book with its properties
class Book
{
    public string Title { get; set; } // Title of the book
    public string Author { get; set; } // Author of the book
    public string Genre { get; set; } // Genre of the book
    public string Summary { get; set; } // Summary of the book

    // Constructor to initialize the book properties
    public Book(string title, string author, string genre, string summary)
    {
        Title = title; // Assign the title of the book
        Author = author; // Assign the author of the book
        Genre = genre; // Assign the genre of the book
        Summary = summary; // Assign the summary of the book
    }
}

// Define a class to handle the persistence (save/load) of book data to/from an SQLite database
class BookDataPersistence
{
    private string connectionString; // Connection string to connect to the SQLite database

    // Constructor to initialize the connection string
    public BookDataPersistence(string connectionString)
    {
        this.connectionString = connectionString; // Store the connection string
    }

    // Method to insert a new book into the SQLite database
    public void AddBook(Book book)
    {
        // SQL query to insert a new book into the Books table
        string query = "INSERT INTO Books (Title, Author, Genre, Summary) VALUES (@Title, @Author, @Genre, @Summary);";

        // Establish a connection to the SQLite database
        using (SQLiteConnection conn = new SQLiteConnection(connectionString))
        {
            // Open the connection
            conn.Open();

            // Create a SQLiteCommand to execute the query
            using (SQLiteCommand cmd = new SQLiteCommand(query, conn))
            {
                // Add parameters to prevent SQL injection
                cmd.Parameters.AddWithValue("@Title", book.Title);
                cmd.Parameters.AddWithValue("@Author", book.Author);
                cmd.Parameters.AddWithValue("@Genre", book.Genre);
                cmd.Parameters.AddWithValue("@Summary", book.Summary);

                // Execute the query to insert the data
                cmd.ExecuteNonQuery();
            }
        }
    }

    // Method to display all books in the database
    public void DisplayBooks()
    {
        // SQL query to select all books from the Books table
        string query = "SELECT * FROM Books;";

        // Establish a connection to the SQLite database
        using (SQLiteConnection conn = new SQLiteConnection(connectionString))
        {
            // Open the connection
            conn.Open();

            // Create a SQLiteCommand to execute the query
            using (SQLiteCommand cmd = new SQLiteCommand(query, conn))
            {
                // Execute the query and get a SQLiteDataReader to read the results
                using (SQLiteDataReader reader = cmd.ExecuteReader())
                {
                    // Print each book from the result set
                    while (reader.Read())
                    {
                        // Display each book's data
                        Console.WriteLine($"ID: {reader["Id"]}");
                        Console.WriteLine($"Title: {reader["Title"]}");
                        Console.WriteLine($"Author: {reader["Author"]}");
                        Console.WriteLine($"Genre: {reader["Genre"]}");
                        Console.WriteLine($"Summary: {reader["Summary"]}");
                        Console.WriteLine("-------------------------------------");
                    }
                }
            }
        }
    }
}

// Main class to demonstrate the functionality
class Program
{
    static void Main(string[] args)
    {
        // Connection string to the SQLite database (SQLite creates the database file if it doesn't exist)
        string connectionString = "Data Source=Books.db;Version=3;";

        // Create an instance of BookDataPersistence to handle database operations
        BookDataPersistence persistence = new BookDataPersistence(connectionString);

        // Ask the user for book information
        Console.WriteLine("Enter book title:");
        string title = Console.ReadLine(); // Read the title of the book

        Console.WriteLine("Enter book author:");
        string author = Console.ReadLine(); // Read the author of the book

        Console.WriteLine("Enter book genre:");
        string genre = Console.ReadLine(); // Read the genre of the book

        Console.WriteLine("Enter book summary:");
        string summary = Console.ReadLine(); // Read the summary of the book

        // Create a Book object with the user's input
        Book newBook = new Book(title, author, genre, summary);

        // Add the new book to the database
        persistence.AddBook(newBook);

        // Display all books in the database
        Console.WriteLine("\nBooks in the database:");
        persistence.DisplayBooks(); // Display all books in the database
    }
}

 Share this C# exercise

 More C# Programming Exercises of Access To Relational Databases

Explore our set of C# programming exercises! Specifically designed for beginners, these exercises will help you develop a solid understanding of the basics of C#. From variables and data types to control structures and simple functions, each exercise is crafted to challenge you incrementally as you build confidence in coding in C#.

  •  Database query

    In this exercise, you need to create a program that displays the data about the books that your previous program has stored in the SQLite database. The goal of this ...

  •  Full acces to a database

    In this exercise, you need to create a program that allows the user to enter information about books and browse the existing data. The program should handle the case where t...