Created
June 11, 2015 14:01
-
-
Save pm-kartik-sura/0071a696c1de090f01a3 to your computer and use it in GitHub Desktop.
MySQL query
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" | |
| // without the underscore _, you will get imported but not | |
| // used error message | |
| _ "github.com/go-sql-driver/mysql" | |
| "os" | |
| ) | |
| func main() { | |
| // connect to our database server with data source name | |
| // data source name configuration has the following parameters : | |
| // [username[:password]@][protocol[(address)]]/dbname[?param1=value1&...¶mN=valueN] | |
| // example config : | |
| // user:password@tcp(127.0.0.1:3306)/database | |
| conn, err := sql.Open("mysql", "db_username:db_password@protocol(address:port_num)/database_name") | |
| if err != nil { | |
| fmt.Println(err) | |
| os.Exit(1) | |
| } | |
| // use your own select statement | |
| // this is just an example statement | |
| statement, err := conn.Prepare("select title from posts limit 10") | |
| if err != nil { | |
| fmt.Println(err) | |
| os.Exit(1) | |
| } | |
| rows, err := statement.Query() // execute our select statement | |
| if err != nil { | |
| fmt.Println(err) | |
| os.Exit(1) | |
| } | |
| for rows.Next() { | |
| var title string | |
| rows.Scan(&title) | |
| fmt.Println("Title of tutorial is :", title) | |
| } | |
| conn.Close() | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment