Created
July 14, 2014 18:55
-
-
Save johnvilsack/44a32afa03f2512a58ae to your computer and use it in GitHub Desktop.
Go: Idiomatic SELECT for MySQL
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/go-sql-driver/mysql" | |
) | |
var ( | |
FirstName string | |
LastName string | |
) | |
const ( | |
connStr = "dbuser:dbpass@tcp(127.0.0.1:3306)/dbname" | |
) | |
func main() { | |
// Database connection - We're using a const here for the string | |
db, err := sql.Open("mysql", connStr) | |
if err != nil { | |
log.Fatal(err) | |
} | |
defer db.Close() | |
// The query. defer rows.Close() always or risk splooging your MySQL database | |
// Query returns many, QueryRow will get you your 1 | |
rows, err := db.Query("SELECT FirstName, LastName FROM dbtable WHERE LastName = ? LIMIT 10", "Smith") | |
if err != nil { | |
log.Fatal(err) | |
} | |
defer rows.Close() | |
// Your loop | |
for rows.Next() { | |
err := rows.Scan(&FirstName, &LastName) | |
if err != nil { | |
log.Fatal(err) | |
} | |
// Always check to see if the loop had any failures. | |
err = rows.Err() | |
if err != nil { | |
log.Fatal(err) | |
} | |
log.Println(FirstName, LastName) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment