How to use SQLite
Last updated
Was this helpful?
Last updated
Was this helpful?
SQLite is an open source, embedded relational database. It has a self-contained, zero-configuration and transaction-supported database engine. Its characteristics are highly portable, easy to use, compact, efficient and reliable. In most of cases, you only need a binary file of SQLite to create, connect and operate a database. If you are looking for an embedded database solution, SQLite is worth considering. You can say SQLite is the open source version of Access.
There are many database drivers for SQLite in Go, but many of them do not support the database/sql
interface standards.
supports database/sql
, based on cgo.
doesn't support database/sql
, based on cgo.
doesn't support database/sql
, based on cgo.
The first driver is the only one that supports the database/sql
interface standard in its SQLite driver, so I use this in my projects -it will make it easy to migrate my code in the future if I need to.
We create the following SQL:
An example:
You may have noticed that the code is almost the same as in the previous section, and that we only changed the name of the registered driver and called sql.Open
to connect to SQLite in a different way.
Note that sometimes you can't use the for
statement because you don't have more than one row, then you can use the if
statement
Also you have to do a rows.Next()
, without using that you can't fetch data in the Scan
function.
The above example shows how you fetch data from the database, but when you want to write a web application then it will not only be necessary to fetch data from the db but it will also be required to write data into it. For that purpose, you should use transactions because for various reasons, such as having multiple go routines which access the database, the database might get locked. This is undesirable in your web application and the use of transactions is effective in ensuring your database activities either pass or fail completely depending on circumstances. It is clear that using transactions can prevent a lot of things from going wrong with the web app.
As it is clear from the above block of code, you first prepare a statement, after which you execute it, depending on the output of that execution then you either roll it back or commit it.
As a final note on this section, there is a useful SQLite management tool available:
Previous section:
Next section: