Connect to PostgreSQL and Run a Query
·
303 words
·
2 minutes read
Sometimes getting a database connection up and running can be a bit fiddly, we’ve all been there, and it can help to have an example to work from. This post aims to show you the complete basics of creating a database connection, forming a query to run and populating a struct with our resulting data.
To do with we use the database/sql
interface and load in the pq
driver/library to actually do the work for us. We’re using QueryRow()
which will only return the single row. If you need more than one row you can use Query()
which returns multiple rows for you to turn each into a struct.
Note: This should be very similar to connecting to CockroachDB
|
|
As a reference, this code uses a very basic schema structure:
|
|