...

/

Solution 3: Go Packages and Functions

Solution 3: Go Packages and Functions

Let’s solve the challenges set in the previous lesson.

Solution 1

Here’s the rewritten code for getSchema.go that works with the jackc/pgx package:

DROP DATABASE IF EXISTS go;
CREATE DATABASE go;

DROP TABLE IF EXISTS Users;
DROP TABLE IF EXISTS Userdata;

\c go;

CREATE TABLE Users (
    ID SERIAL,
    Username VARCHAR(100) PRIMARY KEY
);

CREATE TABLE Userdata (
    UserID Int NOT NULL,
    Name VARCHAR(100),
    Surname VARCHAR(100),
    Description VARCHAR(200)
);
getSchema.go

Code explanation

  • Line 8: First, we will import the pgx package.

  • Lines 32–46: Next, we use pgx to parse the connection string and open a connection to the database. This code is similar to the sql.Open call in the original code. We create a connection string from the arguments, parse it using pgx.ParseConnectionString, and then open a connection to the database ...