MySQL is a very simple and practical database. Currently, it can be integrated with many programming languages. Although the go language is quite young, it seems that it will always be used to catch up with the trend. I just tried the go language to operate the MySQL database. It seems that the amount of code is much less than that of practical Java, which is quite cool.
1. Download the driver
Https://github.com/go-sql-driver/mysql
2. Put this package in the code.google.com directory (it doesn't matter where it is stored, as long as you can let the program find it)
3. Compile a simple test program
package mainimport (_ "code.google.com/mysql""database/sql""fmt")func main() {//format "user:password@tcp(ip:port)/database"db, err := sql.Open("mysql", "root:@tcp(127.0.0.1:3306)/test?charset=utf8")if err != nil {fmt.Println("error in connect ", err.Error())return}fmt.Println("connect ok")rows, err := db.Query("select * from stu")if err != nil {fmt.Println("error in select ", err.Error())return}if rows == nil {fmt.Println("rows is nil")return}for rows.Next() {var u, p stringe := rows.Scan(&u, &p)if e != nil {fmt.Println("err", e.Error())return}fmt.Println(u, " ", p)}}
According to my understanding, in the SQL. Open method, the first parameter is the driver, which is the package we just added. We just introduced it in, so the first line of import is the driver. The second parameter is prone to errors. The format is quite different from that written in Java. However, basically there is no error in writing according to the above format. Compared with JDBC, it writes the load driver and the database to a method, saving a lot of code.
This is just a simple attempt. If you have time, check whether complicated operations are supported.