Golang远程操作MySQL数据库

启动远程数据库

导入mysql引擎包

package main

import (
	"database/sql"

	_ "github.com/go-sql-driver/mysql"
)

type video struct {
	Url   string `json:url`
	Title string `json:title`
	M3u8  string `json:m3u8`
}

func mysql() {
	db, err := sql.Open("mysql", "root:xxxxx@tcp(xxx.xxx.xxx.xxx:3306)/videos")
	if err != nil {
		println(err.Error())
		return
	}
	insertVideo(db, "baidu.com", "baidu", "baidu.m3u8")
	v := queryVideo(db, "baidu.com")
	if v != nil {
		println(v.Url)
		println(v.Title)
		println(v.M3u8)
	}
}

func insertVideo(db *sql.DB, url, title, m3u8 string) {
	res, err := db.Exec("insert into video(url, title, m3u8) value(?, ?, ?)", url, title, m3u8)
	if err != nil {
		println(err.Error())
		return
	}
	println(res.LastInsertId())
}

func queryVideo(db *sql.DB, url string) *video {
	res := db.QueryRow("select * from video where url=?", url)
	v := &video{}
	err := res.Scan(&v.Url, &v.Title, &v.M3u8)
	if err != nil {
		println(err.Error())
		return nil
	}
	return v
}

在第一次运行时,报错:

Error 1130: Host 'xxx.xxx.xxx.xxx' is not allowed to connect to this MySQL server

报错原因是不允许访问数据库,因为mysql中限制了访问该数据库的IP,修改参数放开限制

mysql> use mysql;
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A

Database changed
mysql> 
mysql> select host from user where user='root';
+-----------+
| host      |
+-----------+
| localhost |
+-----------+
1 row in set (0.00 sec)

mysql> update user set host = '%' where user ='root';
Query OK, 1 row affected (0.01 sec)
Rows matched: 1  Changed: 1  Warnings: 0

mysql> select host from user where user='root';
+------+
| host |
+------+
| %    |
+------+
1 row in set (0.00 sec)

mysql> flush privileges;
Query OK, 0 rows affected (0.00 sec)

放开限制之后,再次运行,可以在数据库中查看写入的值

mysql> use videos 
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A

Database changed
mysql> select * from video;
+-----------+-------+------------+
| url       | title | m3u8       |
+-----------+-------+------------+
| baidu.com | baidu | baidu.m3u8 |
+-----------+-------+------------+
1 row in set (0.00 sec)

总结

从上面的例子可以看出,可以使用:

	db, err := sql.Open("mysql", "root:Xjp786..@tcp(43.135.33.233:3306)/videos")
	if err != nil {
		println(err.Error())
		return
	}
	// 获取db对象
	res, err := db.Exec("insert into video(url, title, m3u8) value(?, ?, ?)", url, title, m3u8)
	if err != nil {
		println(err.Error())
		return
	}

通过打开数据库对象之后,可以通过db.Exec()方法来执行sql语句了,这里已以读写为范例,就不去演示其他的增删改查了

你可能感兴趣的:(MySQL,数据库,mysql,golang)