Insert to PostGres
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"database/sql" | |
"log" | |
_ "github.com/lib/pq" | |
) | |
func connect(driver string, credentials string) *sql.DB { | |
db, connectErr := sql.Open(driver, credentials) | |
if connectErr != nil { | |
panic("Could not connect to database") | |
} | |
return db | |
} | |
func insert(conn *sql.DB) { | |
insertSQL := `INSERT INTO users (name, password) VALUES ($1, $2)` | |
result, execErr := conn.Exec(insertSQL, "admin", "secret") | |
if execErr != nil { | |
log.Println("Exec err:", execErr) | |
} | |
log.Printf("Result: %+v\n", result) | |
} | |
func main() { | |
db := connect("postgres", "host=localhost port=5432 dbname=aspect user=postgres password=gotest") | |
defer db.Close() | |
insert(db) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment