Keep in mind: this is the driver package (what we use to communicate with the database) and not SQLite itself. First, up top, we need to import sqlite3 from the package we installed earlier via NPM. Let's get started by wiring up a connection to a database (if it doesn't exist, our driver will create it for us) and then add a table to it.Ĭonst db = new SQLite3.Database('posts.db') A table within that database to organize our data.To get started with our code, we want to make sure we have two things available to us: To keep things simple, SQLite offers a limited set of data types (just five: NULL, INTEGER, REAL(FLOAT), TEXT, and BLOB). When you use a driver to interact with SQLite, you read from and write to this file. A "database" in SQLite is just a file like posts.db or users.db. A SQL based-database that operates as a single file using a special format to store its data. The most popular option for this type of database is SQLite. These are databases that do not require a server to function, meaning they can run in resource-limited environments (e.g., a Raspberry Pi). To combat this, we have a different form of database known as an embedded database. In some cases, though, these sorts of databases are problematic, namely, when you're trying to keep as light a footprint as possible or limit the number of "expensive" (in terms of CPU and memory) processes running alongside your application. In order for these databases to work, though, they need a database server: a long-running process that handles inbound connections.įor a full-blown application, these sorts of databases are helpful because they offer a rich feature set and allow you to manage significant amounts of data. When most people think of a database, they think of something that writes and retrieves data from the disk (like PostgreSQL), or, directly from memory (like Redis). With that in place, we're ready to get started. This will enable ESModules support and allow us to use the import statements shown in the code below. One last step: in the package.json file that was created for you, make sure to add the field "type": "module" as a property. The first will give us access to a Node.js driver for SQLite (what we'll use to connect to the database in our code), while the second will help us generate some test data to insert into our database. Next, we want to install two extra dependencies, sqlite3 and lorem-ipsum: Next, cd into that directory and create an index.js file (this is where we'll write our code for the tutorial): Once you have Node.js installed on your computer, from your projects folder on your computer (e.g., ~/projects), create a new folder for our work: If you don't already have Node.js installed on your computer, read this tutorial first and then come back here. Because the code we're writing for this tutorial is "standalone" (meaning it's not part of a bigger app or project), we're going to create a Node.js project from scratch.
0 Comments
Leave a Reply. |