Last active
December 13, 2015 18:18
-
-
Save atomaths/4953725 to your computer and use it in GitHub Desktop.
Go database/sql and mymysql package usage
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/ziutek/mymysql/godrv" | |
) | |
func OpenDB() *sql.DB { | |
db, err := sql.Open("mymysql", fmt.Sprintf("tcp:%s*%s/%s/%s", DB_HOST, DB_NAME, DB_USER, DB_PASS)) | |
if err != nil { | |
panic(err) | |
} | |
return db | |
} | |
func main() { | |
db := OpenDB() | |
defer db.Close() | |
stmt, err := db.Prepare("SELECT title, content FROM memo WHERE id = ?") | |
defer stmt.Close() | |
id := 123 | |
rows, err := stmt.Query(id) | |
defer rows.Close() | |
if err != nil { | |
panic(err) | |
} | |
if rows.Next() == false { | |
return | |
} | |
var title, content string | |
rows.Scan(&title) | |
rows.Scan(&content) | |
fmt.Printf("%s - %s\n", title, content) | |
return | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment