I have a web server that connects to a postgresql database. As I understand, postgresql driver manages a connection pool internally so I made the database connection a global variable.
I am using prepared statements and I do not know whether it is a good idea to prepare them in advance in my main
function before the server has started, or do it in my request handlers (as below). I am new to golang. I think it is more efficient to make the statements global, but I am not sure. Please help.
var db *sql.DB
func main() {
router = pat.New()
router.Get("/", handler)
db, e := sql.Open("postgres", "...")
...
http.ListenAndServe("127.0.0.1", router)
}
func handler(w http.ResponseWriter, r *http.Request) {
s, e := db.Prepare("select * from mytable where field=$1")
r, e := s.Exec(123)
...
}
A prepared statement is a server-side object that can be used to optimize performance. When the PREPARE statement is executed, the specified statement is parsed, analyzed, and rewritten. When an EXECUTE command is subsequently issued, the prepared statement is planned and executed.
Install Go and pq connector Change directory into the project folder, such as cd %USERPROFILE%\go\src\postgresqlgo . Set the environment variable for GOPATH to point to the source code directory. set GOPATH=%USERPROFILE%\go . Install the Pure Go Postgres driver (pq) by running the go get github.com/lib/pq command.
Go — as this is our programming language of choice, we need to install it in our local environment. PostgreSQL — we will be using PostgreSQL as our database. So, for development purposes, you will need to install it in your local environment.
pq: SSL is not enabled on the server By default, sslmode is set to required with lib/pq , so you need to actually specify another setting to fix this. Update your connection string to include sslmode=disable and you should be back in action.
It all depends on your use case. As a rule of thumb, I would say that you should prepare your statements before running your server, for multiple reasons:
As for your database handle, you should make the statements global to have them handy at any time without having to pass pointers around. If you find yourself juggling with many statements, like more than 10-15 (arbitrary number), you will probably find it easier to put all DB-related stuff (DB initialization, queries, etc) into a sub-package of your main package.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With