Created
February 18, 2016 17:03
-
-
Save bpowell/89294699487714b320fb to your computer and use it in GitHub Desktop.
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" | |
"github.com/lib/pq" | |
) | |
type DatabaseInfo struct { | |
Username string | |
Password string | |
Host string | |
DbName string | |
} | |
type Data struct { | |
Col1 string | |
Col2 string | |
Col3 string | |
} | |
func bulk_insert(db *sql.DB, data []Data) error { | |
transaction, err := db.Begin() | |
if err != nil { | |
fmt.Println(err) | |
return err | |
} | |
statement, err := transaction.Prepare(pq.CopyIn("tablename", "col1", "col2", "col3")) | |
if err != nil { | |
fmt.Println(err) | |
return err | |
} | |
for _, d := range data { | |
_, err = statement.Exec(d.Col1, d.Col2, d.Col3) | |
if err != nil { | |
fmt.Println(err) | |
return err | |
} | |
} | |
if err = statement.Close(); err != nil { | |
fmt.Println(err) | |
return err | |
} | |
if err = transaction.Commit(); err != nil { | |
fmt.Println(err) | |
return err | |
} | |
} | |
func query_for_multiple_rows(db *sql.DB, query string) ([]Data, error) { | |
var datas []Data | |
rows, err := db.Query(query) | |
if err != nil { | |
fmt.Println(err) | |
return datas, err | |
} | |
defer rows.Close() | |
for rows.Next() { | |
var d Data | |
if err = rows.Scan(&d.Col1, &d.Col2, &d.Col3); err != nil { | |
fmt.Println(err) | |
} else { | |
datas = append(datas, d) | |
} | |
} | |
return datas, nil | |
} | |
func query_for_single_row(db *sql.DB, query string, id int) (Data, error) { | |
var data Data | |
if err := database.QueryRow(query, id).Scan(&d.Col1, &d.Col2, &d.Col3); err != nil { | |
fmt.Println(err) | |
return Data{}, err | |
} | |
return data, nil | |
} | |
func main() { | |
var dbInfo DatabaseInfo | |
//Fill out dbInfo before this call | |
dbURL := fmt.Sprintf("postgres://%s:%s@%s/%s", dbInfo.Username, dbInfo.Password, dbInfo.Host, dbInfo.DbName) | |
db, err := sql.Open("postgres", dbURL) | |
if err != nil { | |
fmt.Println(err) | |
return | |
} | |
//Both db.Query and db.QueryRow take variable amount of arguments | |
// the first being the SQL string and the rest the variables | |
// that are being passed to the query | |
fmt.Println(query_for_multiple_rows(db, "select * from data")) | |
fmt.Println(query_for_single_row(db, "select * from data where id = $1", 1)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment