-
-
Save up1/a4e539ddf66e4b4bbcd9 to your computer and use it in GitHub Desktop.
Demo :: Go with database
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" | |
_ "github.com/go-sql-driver/mysql" | |
) | |
func main() { | |
db, err := sql.Open("mysql", "user1:user1password@/todo") | |
if err != nil { | |
panic(err.Error()) | |
} | |
defer db.Close() | |
err = db.Ping() | |
if err != nil { | |
panic(err.Error()) | |
} | |
} |
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
statementInsert, err := db.Prepare("INSERT INTO task VALUES( ?, ? )") | |
if err != nil { | |
panic(err.Error()) | |
} | |
defer statementInsert.Close() | |
result, err := statementInsert.Exec(0, "task 1") | |
if err != nil { | |
panic(err.Error()) | |
} | |
lastID, err := result.LastInsertId() | |
fmt.Printf("Last ID=%d\n", lastID) |
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
statementQuery, err := db.Prepare("SELECT task_id, title FROM task") | |
if err != nil { | |
panic(err.Error()) | |
} | |
defer statementQuery.Close() | |
rows, err := statementQuery.Query() | |
if err != nil { | |
panic(err.Error()) | |
} | |
defer rows.Close() | |
for rows.Next() { | |
var id int | |
var title string | |
rows.Scan(&id, &title) | |
fmt.Printf("ID=%d, Title=%s\n", id, title) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment