
Introduction
In the previous post Connecting to PostgreSQL from Go lang project, we learned how to connect to the PostgreSQL database from Go lang project using database/sql
package that ships with Go, along with github.com/lib/pq
Postgres driver. In this post, we’ll learn how to insert data (rows) in a PostgreSQL table.
Prerequisites
To be able to achieve our objective i.e. Inserting rows to PostgreSQL from Go , there are some prerequisites. Sticking to the core subject of this blog, I won’t cover them, however, I’m providing with useful references:
-
- Install PostgreSQL, setup an instance and create a test database – https://www.postgresqltutorial.com/install-postgresql/
-
- Install Go and configure workspace – https://www.callicoder.com/golang-installation-setup-gopath-workspace/
For purpose of this tutorial, I’m using Postgres 11 and Go 1.13.xx
Objective – Inserting rows to a PostgreSQL table from Go
In following steps, I’ll demonstrate how to write a simple command-line tool (CLI) using Go lang to insert rows in PostgreSQL database table
Step 1. SQL Table definition
Create test table EMP in PostgreSQL test database with the following columns
-- create a sample table EMP
CREATE TABLE emp (
empno SERIAL PRIMARY KEY,
ename TEXT,
sal INT,
email TEXT UNIQUE NOT NULL
);
Step 2. SQL Insert statement
a basic SQL INSERT statement will look something like this
INSERT INTO public.emp (ename, sal, email)
VALUES('Smith', 800, 'smith@acme.com');
Step 3. Connecting to PostgreSQL instance
To be able to insert a row in the database, we first need to connect to the instance. In earlier post in this series we learned how to connect to PostgreSQL from Go lang project using database/sql
package. I was originally using the same connection string, when one of the readers suggested me a better approach i.e. to use const()
construct for declaring connection string variable
const (
host = "localhost"
port = 5432
user = "postgres"
password = "secure-password"
dbname = "connect-db"
)
Next in our main()
function we are going to create a string variable connStr
which contains all of the information required to connect to our Postgres database.
func main() {
// connection string
connStr := fmt.Sprintf("host=%s port=%d user=%s "+
"password=%s dbname=%s sslmode=disable",
host, port, user, password, dbname)
}
Step 4. Preparing Go lang code to insert row in EMP table
In our Go code, we’ll use same SQL statement and calling db.Exec()
method on sql.db
object. A thing to note is here is db.Exec()
returns two values – a result and an error. We’re using the later for error handling, to generate a panic()
if anything goes wrong.
sqlStatement := `INSERT INTO emp (ename, sal, email)
VALUES ($1, $2, $3)`
_, err = db.Exec(sqlStatement, "Smith", 800, "smith@acme.com")
if err != nil {
panic(err)
}
Step 5. Putting this all together
package main
// inserting records into a PostgreSQL database with Go's database/sql package
import (
"database/sql"
"fmt"
_ "github.com/lib/pq"
)
const (
host = "pgslx1005"
port = 5432
user = "postgres"
password = "postgres"
dbname = "connect-db"
)
func main() {
connStr := fmt.Sprintf("host=%s port=%d user=%s "+
"password=%s dbname=%s sslmode=disable",
host, port, user, password, dbname)
db, err := sql.Open("postgres", connStr)
if err != nil {
panic(err)
}
defer db.Close()
// insert a row
sqlStatement := `INSERT INTO emp (ename, sal, email)
VALUES ($1, $2, $3)`
_, err = db.Exec(sqlStatement, "Smith", 800, "smith@acme.com")
if err != nil {
panic(err)
} else {
fmt.Println("\nRow inserted successfully!")
}
}
After inserting some additional rows, EMP table now looks like this
| empno | ename | sal | email |
|-------|-------|------|----------------|
| 11 | Smith | 800 | smith@acme.com |
| 12 | Allen | 1000 | allen@acme.com |
| 13 | Jones | 1200 | jones@acme.com |
| 14 | Blake | 1400 | blake@acme.com |
Conclusion
In this post we learned how to INSERT records (rows) in PostgreSQL db table via Go lang project. In the next post, I’ll explain about remaining two DML operations i.e. UPDATE and DELETE.
Like what I write? Please join my mailing list, and I’ll let you know whenever I write another post. No spam, I promise! 👨💻
2 thoughts on “Inserting rows in PostgreSQL db from Go lang project”