7-24 2,472 views
参考 https://tutorialedge.net/golang/golang-mysql-tutorial/
使用文档 : https://sqlchoice.azurewebsites.net/en-us/sql-server/developer-get-started/go/sles/step/2.html
文档2:http://www.golangprograms.com/example-of-golang-crud-using-mysql-from-scratch.html连接
package main
import (
"fmt"
"database/sql"
_ "github.com/go-sql-driver/mysql"
)
func main() {
fmt.Println("Go MySQL Tutorial")
// Open up our database connection.
// I've set up a database on my local machine using phpmyadmin.
// The database is called testDb
db, err := sql.Open("mysql", "username:password@tcp(127.0.0.1:3306)/test")
// if there is an error opening the connection, handle it
if err != nil {
panic(err.Error())
}
// defer the close till after the main function has finished
// executing
defer db.Close()
}
简单查询
package main
import (
"fmt"
"database/sql"
_ "github.com/go-sql-driver/mysql"
)
func main() {
fmt.Println("Go MySQL Tutorial")
// Open up our database connection.
// I've set up a database on my local machine using phpmyadmin.
// The database is called testDb
db, err := sql.Open("mysql", "root:password1@tcp(127.0.0.1:3306)/test")
// if there is an error opening the connection, handle it
if err != nil {
panic(err.Error())
}
// defer the close till after the main function has finished
// executing
defer db.Close()
// perform a db.Query insert
insert, err := db.Query("INSERT INTO test VALUES ( 2, 'TEST' )")
// if there is an error inserting, handle it
if err != nil {
panic(err.Error())
}
// be careful deferring Queries if you are using transactions
defer insert.Close()
}
查询单条
var tag Tag
// Execute the query
err = db.QueryRow("SELECT id, name FROM tags where id = ?", 2).Scan(&tag.ID, &tag.Name)
if err != nil {
panic(err.Error()) // proper error handling instead of panic in your app
}
log.Println(tag.ID)
log.Println(tag.Name)
查询多条
package main
// doc go get -u github.com/go-sql-driver/mysql url:https://github.com/go-sql-driver/mysql
import (
"database/sql"
"fmt"
_ "github.com/go-sql-driver/mysql"
)
type Tag struct {
id int
a string
b string
c string
}
func main() {
db, err := sql.Open("mysql", "root:123456$@tcp(127.0.0.1:3306)/test")
if err != nil {
panic(err.Error())
}
results, err := db.Query("SELECT id,a,b,c FROM test order by id desc")
if err != nil {
panic(err.Error())
}
fmt.Println(results)
for results.Next() {
var tag Tag
err = results.Scan(&tag.id, &tag.a, &tag.b, &tag.c)
if err != nil {
panic(err.Error()) // proper error handling instead of panic in your app
}
// and then print out the tag's Name attribute
fmt.Println("id: ", tag.id)
fmt.Println("a: ", tag.a)
fmt.Println("b: ", tag.b)
fmt.Println("c: ", tag.c)
}
defer db.Close()
}