Last active
January 11, 2016 06:10
-
-
Save aliukevicius/7264abf650ad170f10bc to your computer and use it in GitHub Desktop.
Golang MySQL
This file contains hidden or 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/go-sql-driver/mysql" | |
) | |
func main() { | |
db, err := sql.Open("mysql", "root:root@tcp(172.17.0.2:3306)/test-db") | |
if err != nil { | |
panic(err) | |
} | |
defer db.Close() | |
// we have two fields in table id and name so we need two placeholders or | |
// else we will get an error | |
stmtIns, err := db.Prepare("INSERT INTO names VALUES( ?, ? )") | |
if err != nil { | |
panic(err) | |
} | |
// Close the statement when we leave main() / the program terminates | |
defer stmtIns.Close() | |
// our id field auto increments so we don't need to pass actual value for it. | |
_, err = stmtIns.Exec(nil, "John") | |
if err != nil { | |
panic(err) | |
} | |
// Prepare statement for reading data | |
rows, err := db.Query("SELECT id, name FROM names") | |
if err != nil { | |
panic(err) | |
} | |
defer rows.Close() | |
var id int | |
var name string | |
for rows.Next() { | |
rows.Scan(&id, &name) | |
fmt.Printf("%d : %s \n", id, name) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment