In order to communicate with MySQL using Go, MySQL must be installed in your local machine so that you are able to use it. We will also use the database/sql
package in Go’s standard library with any of the MySQL drivers so that connection to MySQL can be achieved.
Some of the available drivers for MySQL are:
github.com/go-sql-driver/mysql/
github.com/siddontang/go-mysql/
github.com/ziutek/mymysql
For this shot, we will be using the
github.com/go-sql-driver/mysql/
.
CRUD stands for Create, Read, Update, Delete. Below are steps for how to set up a connection as well as read from MySQL database using Go:
mysql --version
in our terminal. The resulting version means we have MySQL installed.mysql driver package
in our project:
go get -u github.com/go-sql-driver/mysql
.database/sql
and github.com/go-sql-driver/mysql
in our program.package mainimport ("database/sql"_ "github.com/go-sql-driver/mysql""fmt""log")func main(){fmt.Println("How to Use Go with MySQL")}
sql.Open("<driverName>","<databaseSource>")
command. This command returns a pointer to the database. The driver name for our project is "mysql"
, and the databaseSource
is a string of "<databaseUserName>:<password>@tcp(localhost:<port>)/<databaseName>"
.// already imported used packages in the first code blockfunc main(){db,err := sql.Open("mysql","root:password@tcp(localhost:3306)/testdb") //newdefer db.Close() //newerrCheck(err) //new}//newfunc errCheck(err error){if err != nil{log.Fatal(err)}}
Ping()
method from the database/sql
package. If an error is returned, it means that the database is unavailable.func main(){err = db.Ping() //newerrCheck(err) //new}
type Todo struct {ID int `json:"id"`Name string `json:"name"`}var db *sql.DBfunc main(){db,_ = sql.Open("mysql","root:password@tcp(localhost:3306)/testdb") // modifiedgetAll() // get all the todos in the databasegetASingleTodo(1) // get the first todo}func getAll(){// get all todo from the todos table// note err has already been defined earlier as well as the errCheck functiontodos, err := db.Query("SELECT * FROM todos")errCheck(err)for todos.Next() {var todo Todo// for each row, scan the result into our todo composite objecterr = todos.Scan(&todo.ID, &todo.Name)errCheck(err)// print out the todo's Name attributelog.Printf(todo.Name)}}func getASingleTodo(id int){// get a single todo based on the idvar todo Todoerr := db.QueryRow("SELECT * FROM todos where id = ?", id).Scan(&todo.ID, &todo.Name)errCheck(err)log.Printf("%d) %s\n",todo.ID,todo.Name)}
We have seen how to set up MySQL to enable us to use Go with it as well as read data from it. There are also other queries that we can send to the database using Go – click here for more information.