Objective
Create a program to display the data about books which your previous program has stored.
Write Your C# Exercise
C# Exercise Example
// Importing necessary namespaces for SQLite operations and basic functionalities
using System; // For basic functionalities like Console and Exception handling
using System.Data.SQLite; // For SQLite operations
// Define a class to handle the database operations for querying the books
class BookDataQuery
{
private string connectionString; // Connection string to connect to the SQLite database
// Constructor to initialize the connection string
public BookDataQuery(string connectionString)
{
this.connectionString = connectionString; // Store the connection string
}
// Method to display all books stored in the SQLite 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
Console.WriteLine("Books in the database:");
Console.WriteLine("-------------------------------------");
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 BookDataQuery to handle database query operations
BookDataQuery query = new BookDataQuery(connectionString);
// Display all books stored in the database
query.DisplayBooks();
}
}
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#.
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...
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 da...