Created
August 18, 2016 20:29
-
-
Save eikaas/8cd859000b9e3500174bf2e114cc58dc to your computer and use it in GitHub Desktop.
PostgreSQL: Create table, insert row
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" | |
"fmt" | |
"log" | |
_ "github.com/bmizerany/pq" | |
) | |
/* PostgreSQL in Go: Create table & Insert row | |
1. Create the user and database from the psql cli, as an admin user: | |
% psql | |
postgres=# CREATE USER alpha_user with password 'alpha01'; | |
postgres=# CREATE DATABASE alpha_db01 OWNER alpha_user; | |
*/ | |
// 2. This table will be created (If it doesnt already exist) so that we can insert some shit: | |
var create_person_table = ` | |
CREATE TABLE IF NOT EXISTS person( | |
id serial primary key, | |
username varchar not null, | |
first_name varchar, | |
last_name varchar, | |
email varchar | |
);` | |
// 3. The admin user will be inserted | |
var insert_admin_user = ` | |
INSERT INTO person(username, first_name, last_name, email) | |
VALUES('admin', 'Admin', 'Administrator', 'admin@localhost'); | |
` | |
// 4. The db, which represents a database - not a database connection, is defined globally. | |
var db sql.DB | |
func main() { | |
dbuser := "alpha_user" | |
dbname := "alpha_db01" | |
dbpass := "alpha01" | |
dbport := "5432" | |
db, err := sql.Open("postgres", | |
fmt.Sprintf("dbname=%s user=%s password=%s port=%s sslmode=disable", dbname, dbuser, dbpass, dbport)) | |
defer db.Close() | |
if err != nil { | |
log.Panic(err) | |
} | |
err = db.Ping() | |
if err != nil { | |
log.Panic(err) | |
} | |
_, err = db.Exec(create_person_table) | |
if err != nil { | |
log.Panic(err) | |
} | |
fmt.Println("Table created!") | |
_, err = db.Exec(insert_admin_user) | |
if err != nil { | |
log.Panic(err) | |
} | |
fmt.Println("Admin user created") | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment