Below is a very basic snippet that shows how to write to an SQLite database using Go.
One note about the code snippet below — in it, I’m using the modernc.org/sqlite package rather than the (more popular) mattn/go-sqlite3 package. This is because the former doesn’t require CGO or a gcc compiler, which makes it easier to set up. That said, both implementations are compatible with the database/sql
base package, so switching should just be a drop-in replacement
Setup
First, set up a demo database by running the following SQL script (my_script.sql
):
It can be run via:
Go Program
Then the following Go program will write a record into the person
table in demo.db
The basic flow here is:
- Connect to the database via
sql.Open
, which takes two arguments — the driver and the connection string - Prepare a statement using the
db.Prepare()
method, which lets you create a statement using?
as placeholders for arguments to be passed in later. - Execute the statement/query via
stmt.Exec()
, which passes values to the?
placeholders in the result fromdb.Prepare()