2081 11

BIT351 · 2081 · 5 marks

Given a table BOOK(ISBN,Name,Author,Price), write a program to update the price of the book to 1000 whose author is John.

Given a table BOOK(ISBN,Name,Author,Price), write a program to update the price of the book to 1000 whose author is John. [5]

NET Centric ComputingChapter 3: Data Access with ADO.NET and Entity FrameworkCRUD operations with ADO.NETNumerical: SQL update statement

Updating the price of a book from a .NET program

The table is BOOK(ISBN, Name, Author, Price) and the requirement is a single row update: every book whose Author is John must end up with Price set to 1000. The database work itself is one SQL statement.

UPDATE BOOK
SET Price = @price
WHERE Author = @author;

BIT351 is a .NET paper, so the program that carries that statement to the server is written in C#, using either ADO.NET (SqlConnection, SqlCommand, SqlParameter) or Entity Framework Core. Both are acceptable; the ADO.NET version is shown first because it makes the database work explicit.

The ADO.NET version

using System;
using System.Data;
using Microsoft.Data.SqlClient;

public static class Program
{
    public static void Main()
    {
        const string connectionString =
            "Server=localhost;Database=Library;Trusted_Connection=True;TrustServerCertificate=True;";

        const string sql = "UPDATE BOOK SET Price = @price WHERE Author = @author";

        // using declarations close and dispose the connection and command even on an exception.
        using var connection = new SqlConnection(connectionString);
        using var command = new SqlCommand(sql, connection);

        // The two values travel as typed parameters, never as text pasted into the command.
        command.Parameters.Add("@price", SqlDbType.Decimal).Value = 1000m;
        command.Parameters.Add("@author", SqlDbType.NVarChar, 50).Value = "John";

        try
        {
            connection.Open();

            int rows = command.ExecuteNonQuery();

            if (rows > 0)
            {
                Console.WriteLine(rows + " book(s) by John now cost 1000.");
            }
            else
            {
                Console.WriteLine("No book by John was found, so nothing was updated.");
            }
        }
        catch (SqlException ex)
        {
            Console.WriteLine("Database error: " + ex.Message);
        }
    }
}

ExecuteNonQuery is the method used for INSERT, UPDATE and DELETE: it returns the number of rows the statement affected, which is exactly what is needed to report whether any book by John existed. ExecuteReader would be wrong here because an update returns a row count and not a result set, and ExecuteScalar would be wrong because there is no single value to read back.

The flow of the program is the ordinary ADO.NET sequence.

What happensHow
Describe the server, database and credentialsthe connection string
Hold the parameterised command textSqlCommand
Bind the new price and the author safelySqlParameter objects added to command.Parameters
Open the network connectionconnection.Open()
Run the update and read the row countExecuteNonQuery()
Release the connection back to the poolthe using declarations

Why the values are bound and not pasted in

The command text above is a constant. It is fixed at compile time, and the author name and the price reach the server separately, as data. That matters even in a small exam program: if a value such as the author name were joined onto the command text at run time, a name containing a quote or a trailing OR 1=1 would change the meaning of the statement and update every row in the table. That is SQL injection, and escaping quotes by hand is not a substitute for binding, because it depends on the programmer remembering it at every call site. Parameters remove the problem by construction, and they also let the server reuse the cached execution plan.

The Entity Framework Core version

If the project already has a model, the same update is expressed against objects and EF Core writes the parameterised SQL for you.

using System;
using System.Linq;
using Microsoft.EntityFrameworkCore;

[Table("BOOK")]
public class Book
{
    [Key]
    public string ISBN { get; set; } = "";
    public string Name { get; set; } = "";
    public string Author { get; set; } = "";
    public decimal Price { get; set; }
}

public class LibraryContext : DbContext
{
    public DbSet<Book> Books => Set<Book>();

    protected override void OnConfiguring(DbContextOptionsBuilder options) =>
        options.UseSqlServer(
            "Server=localhost;Database=Library;Trusted_Connection=True;TrustServerCertificate=True;");
}

public static class UpdatePrice
{
    public static void Run()
    {
        using var db = new LibraryContext();

        foreach (Book book in db.Books.Where(b => b.Author == "John"))
        {
            book.Price = 1000m;
        }

        int rows = db.SaveChanges();
        Console.WriteLine(rows + " row(s) updated.");
    }
}

The comparison b.Author == "John" is translated into a parameterised WHERE clause, so this version is as safe as the first one, and SaveChanges wraps the writes in a transaction.

If the result is displayed in an ASP.NET Core page rather than a console, print it through Razor (for example @rows), which HTML encodes the value automatically, so a book name or author taken from the database can never be interpreted as markup in the browser.

Short on time? The 1, 5 and 10 mark versions of this answer, flashcards and practice sets come with a program pass.