Connect to a database
1. Get a Database Adapter
To connect to a database, you need an adapter. Use go get
to fetch it like
this:
go get github.com/upper/db/v4/adapter/{$ADAPTER}
Where $ADAPTER
could be any of the following:
postgresql
: for PostgreSQLmysql
: for MySQLsqlite
: for SQLitecockroachdb
: for CockroachDBmongo
: for MongoDBql
: for QL
For instance, if you’d like to use the PostgreSQL adapter, you’d first run:
go get -u github.com/upper/db/v4/adapter/postgresql
to get the adapter, and then you can import it into your project:
import (
"github.com/upper/db/v4/adapter/postgresql"
)
2. Configure a Database Connection
Set the database credentials using the ConnectionURL
type provided by the
adapter:
import (
"github.com/upper/v4/adapter/postgresql"
)
var settings = postgresql.ConnectionURL{
Database: `booktown`,
Host: `postgres`,
User: `demo`,
Password: `b4dp4ss`,
}
Note that the ConnectionURL
(which satisfies the db.ConnectionURL
interface) varies from database engine to another. The connection properties
required by each adapter are explained in detail here.
3. Establish a Connection
Use the Open
function to establish a connection with the database server:
sess, err := postgresql.Open(settings)
...
4. Close the Connection
Set the database connection to close automatically after completing all tasks.
Use Close
and defer
:
defer sess.Close()