GoLang MySQL CRUD Example
本文摘抄自:
https://golangdocs.com/mysql-golang-crud-example
MySQL is one of the most used relational database engines in the world. It provides a simple and clear interface as well as integrations to many different programming languages.
In this post, we will connect to MySQL with GoLang.
Required package
获取链接mysql的驱动
go get -u https://github.com/go-sql-driver/mysql
Go MySQL example
现在,我们来看一看如何使用golang来操作MySQL。
Now, we will take a look at how to use MySQL with Go. Here we are using prepared statements. That is the best way to handle SQL database.
Database structure
This database consists of posts that have id as primary key, name of post and text of the post.
type Post struct {
Id int
Name string
Text string
}
建立数据库连接
To insert first we create a connection and check if it’s working correctly.
db, e := sql.Open("mysql", "<user>:<password>@/<databasename>")
ErrorCheck(e)
// close database after all work is done
defer db.Close()
PingDB(db)
//Where the ping function as following:
func PingDB(db *sql.DB) {
err := db.Ping()
ErrorCheck(err)
}
//The error checking function is simple.
func ErrorCheck(err error) {
if err != nil {
panic(err.Error())
}
}
表结构说明
### CURD中的C, insert into database
//todo