1. Mysql使用

新建test数据库,person、place 表

  1. CREATE TABLE `person` (
  2. `user_id` int(11) NOT NULL AUTO_INCREMENT,
  3. `username` varchar(260) DEFAULT NULL,
  4. `sex` varchar(260) DEFAULT NULL,
  5. `email` varchar(260) DEFAULT NULL,
  6. PRIMARY KEY (`user_id`)
  7. ) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;
  8. CREATE TABLE place (
  9. country varchar(200),
  10. city varchar(200),
  11. telcode int
  12. )ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;
  1. mysql> desc person;
  2. +----------+--------------+------+-----+---------+----------------+
  3. | Field | Type | Null | Key | Default | Extra |
  4. +----------+--------------+------+-----+---------+----------------+
  5. | user_id | int(11) | NO | PRI | NULL | auto_increment |
  6. | username | varchar(260) | YES | | NULL | |
  7. | sex | varchar(260) | YES | | NULL | |
  8. | email | varchar(260) | YES | | NULL | |
  9. +----------+--------------+------+-----+---------+----------------+
  10. 4 rows in set (0.00 sec)
  11. mysql> desc place;
  12. +---------+--------------+------+-----+---------+-------+
  13. | Field | Type | Null | Key | Default | Extra |
  14. +---------+--------------+------+-----+---------+-------+
  15. | country | varchar(200) | YES | | NULL | |
  16. | city | varchar(200) | YES | | NULL | |
  17. | telcode | int(11) | YES | | NULL | |
  18. +---------+--------------+------+-----+---------+-------+
  19. 3 rows in set (0.01 sec)

1.1.1. mysql使用

使用第三方开源的mysql库: github.com/go-sql-driver/mysql (mysql驱动) github.com/jmoiron/sqlx (基于mysql驱动的封装)

命令行输入 :

  1. go get github.com/go-sql-driver/mysql
  2. go get github.com/jmoiron/sqlx

链接mysql

  1. database, err := sqlx.Open("mysql", "root:XXXX@tcp(127.0.0.1:3306)/test")
  2. //database, err := sqlx.Open("数据库类型", "用户名:密码@tcp(地址:端口)/数据库名")