Start learning free

LESSON 35 OF 173 · BACKEND: SQL

Your First Query in C#

Practice

The shop keeps its data in a database, a file called shop.db. Inside, the data sits in tables. A table is like a list of objects that all have the same fields: each row is one item, and each column is one of its fields. The products table has one row per product, with the columns id, name, price, category and stock.

A SqliteConnection connects your program to the file: new SqliteConnection("Data Source=shop.db") gives you a connection, the line your program talks to the database through. Write it with using var, so it is closed when the program ends. Your questions are written in SQL, as a string. SELECT says which columns you want, and * means all of them; FROM says which table to read. This one reads every column of every customer:

var query = "SELECT * " +
    "FROM customers ";

The + joins the two strings, so query holds one string, "SELECT * FROM customers ". That's why each piece ends with a space: it keeps the words apart. The statement only ends at the ;: a line that ends with + carries on into the next line.

The check runs your query and prints the column names, the rows and how many there are. The gift card has no category, so that value is NULL, SQL's word for "no value", like null in C#. Your code must print:

id | name | price | category | stock
1 | Mug | 12 | kitchen | 10
2 | Notebook | 7 | office | 0
3 | Lamp | 29 | home | 1
4 | Pen | 2 | office | 120
5 | Plant | 15 | home | 6
6 | Teapot | 22 | kitchen | 4
7 | Stapler | 9 | office | 15
8 | Gift card | 50 | NULL | 999
(8 rows)

Your task: make a connection to shop.db with using var and keep it in a variable named db. Then write a query that reads every column of the products table.


Assignment
Follow the Coding Tutorial to connect to the shop's database and write your first query: every column, from the products table.


Hint
The connection string is a string, so it goes in quotes: "Data Source=shop.db". In the query, each piece is its own string ending with a space. Every line but the last ends with +, and the last one ends with ;.


STEP 1 OF 3
    Ctrl + Enter to check

    Sql Select All in C#

    Keep going with C#1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free