Wednesday, April 25, 2018

How do you create database 'objects' in SQLite using command line?

In this post,

You will create a SQLite database and persist in your file system.
You will find the directory where the SQLite database is saved.
You will relaunch SQLite3 and access the persisted SQLite database file.
You will create a table.
You will test for tables in your computer/folder.
You will populate the table with some values.
You will run a SELECT query to find the table contents.

I created a desktop shortcut from the file location of sqlite3.exe in one of my folders and launched it. It opens with a command prompt, sqlite>.

The version is at the beginning of the prompt as shown.
SQLite version 3.23.1 2018-04-10 17:39:29
Enter ".help" for usage hints.
Connected to a transient in-memory database.
Use ".open FILENAME" to reopen on a persistent database.

Creating a database is easy. As shown here it creates a database (file) called 'aloha'.
---------
sqlite> .open aloha
sqlite>

-----------
It creates the database file ("aloha") in the directory which can be seen by the next command. The command .databases without any space after the C: prompt.
------------
sqlite> .databases
main: C:\Users\Owner\Desktop\Blog2017\MSSS2017\SQLite3_DBS\aloha
sqlite>

-------------------
Creating a table is easy as well. The following creates a table 'flower' in the database.
-----------------
sqlite> CREATE TABLE flower ( Id integer PRIMARY KEY, Ename varchar(20), Fname varchar(20));
-------------
Just check if you have any tables using .tables command as shown.
------------------------------------
sqlite> .tables
flower

---------------
Now exit sqlite3.
Launch sqlite3 again.

We will access the saved (persisted) database 'aloha'. Note that double quotes ("") spawns an error as shown. Filename within single quote ('') opens the database
----------------
sqlite> .open "C:\Users\Owner\Desktop\Blog2017\MSSS2017\SQLite3_DBS\aloha"
Error: unable to open database "C:UsersOwnerDesktopBlog2017MSSS2017SQLite3_DBSloha": unable to open database file

sqlite> .open 'C:\Users\Owner\Desktop\Blog2017\MSSS2017\SQLite3_DBS\aloha'
sqlite>

--------------------------------------
Populating the table is also SQL based.
-------------------
sqlite> INSERT INTO flower Values ('1','Hyacinth', 'Jasinth')
   ...> ;

--------------
Now you can run a SELECT query as shown.
--------------
sqlite> SELECT * FROM flower;
1|Hyacinth|Jasinth
sqlite>

-------------------------------

It is continued in the next post tomorrow.

No comments: