1. 程式人生 > >Mysql學習(一)新增一個新的使用者並用golang操作Mysql

Mysql學習(一)新增一個新的使用者並用golang操作Mysql

Mysql新增一個新的使用者並賦予許可權

新增一個自己的使用者到mysql

首先我們需要先用root使用者登入mysql,但是剛安裝完沒有密碼,我們先跳過密碼

[email protected]:~/Git_Project/Go_Test$ sudo mysqld_safe --skip-grant-tables
2019-01-07T01:35:51.559420Z mysqld_safe Logging to syslog.
2019-01-07T01:35:51.563797Z mysqld_safe Logging to '/var/log/mysql/error.log'.

root登陸

[email protected]:~/Git_Project/Go_Test$ sudo mysql -u root
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 4
Server version: 5.7.24-0ubuntu0.18.04.1 (Ubuntu)

Copyright (c) 2000, 2018, Oracle and/or its affiliates. All rights reserved.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;'
or '\h' for help. Type '\c' to clear the current input statement.

切換資料庫, use mysql

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> show tables;
+---------------------------+
|
Tables_in_mysql | +---------------------------+ | columns_priv | | db | | engine_cost | | event | | func | | general_log | | gtid_executed | | help_category | | help_keyword | | help_relation | | help_topic | | innodb_index_stats | | innodb_table_stats | | ndb_binlog_index | | plugin | | proc | | procs_priv | | proxies_priv | | server_cost | | servers | | slave_master_info | | slave_relay_log_info | | slave_worker_info | | slow_log | | tables_priv | | time_zone | | time_zone_leap_second | | time_zone_name | | time_zone_transition | | time_zone_transition_type | | user | | user_info | +---------------------------+ 32 rows in set (0.00 sec)

檢視user表

mysql> desc user;

+------------------------+-----------------------------------+------+-----+-----------------------+-------+
| Field                  | Type                              | Null | Key | Default               | Extra |
+------------------------+-----------------------------------+------+-----+-----------------------+-------+
| Host                   | char(60)                          | NO   | PRI |                       |       |
| User                   | char(32)                          | NO   | PRI |                       |       |
| Select_priv            | enum('N','Y')                     | NO   |     | N                     |       |
| Insert_priv            | enum('N','Y')                     | NO   |     | N                     |       |
| Update_priv            | enum('N','Y')                     | NO   |     | N                     |       |
| Delete_priv            | enum('N','Y')                     | NO   |     | N                     |       |
| Create_priv            | enum('N','Y')                     | NO   |     | N                     |       |
| Drop_priv              | enum('N','Y')                     | NO   |     | N                     |       |
| Reload_priv            | enum('N','Y')                     | NO   |     | N                     |       |
| Shutdown_priv          | enum('N','Y')                     | NO   |     | N                     |       |
| Process_priv           | enum('N','Y')                     | NO   |     | N                     |       |
| File_priv              | enum('N','Y')                     | NO   |     | N                     |       |
| Grant_priv             | enum('N','Y')                     | NO   |     | N                     |       |
| References_priv        | enum('N','Y')                     | NO   |     | N                     |       |
| Index_priv             | enum('N','Y')                     | NO   |     | N                     |       |
| Alter_priv             | enum('N','Y')                     | NO   |     | N                     |       |
| Show_db_priv           | enum('N','Y')                     | NO   |     | N                     |       |
| Super_priv             | enum('N','Y')                     | NO   |     | N                     |       |
| Create_tmp_table_priv  | enum('N','Y')                     | NO   |     | N                     |       |
| Lock_tables_priv       | enum('N','Y')                     | NO   |     | N                     |       |
| Execute_priv           | enum('N','Y')                     | NO   |     | N                     |       |
| Repl_slave_priv        | enum('N','Y')                     | NO   |     | N                     |       |
| Repl_client_priv       | enum('N','Y')                     | NO   |     | N                     |       |
| Create_view_priv       | enum('N','Y')                     | NO   |     | N                     |       |
| Show_view_priv         | enum('N','Y')                     | NO   |     | N                     |       |
| Create_routine_priv    | enum('N','Y')                     | NO   |     | N                     |       |
| Alter_routine_priv     | enum('N','Y')                     | NO   |     | N                     |       |
| Create_user_priv       | enum('N','Y')                     | NO   |     | N                     |       |
| Event_priv             | enum('N','Y')                     | NO   |     | N                     |       |
| Trigger_priv           | enum('N','Y')                     | NO   |     | N                     |       |
| Create_tablespace_priv | enum('N','Y')                     | NO   |     | N                     |       |
| ssl_type               | enum('','ANY','X509','SPECIFIED') | NO   |     |                       |       |
| ssl_cipher             | blob                              | NO   |     | NULL                  |       |
| x509_issuer            | blob                              | NO   |     | NULL                  |       |
| x509_subject           | blob                              | NO   |     | NULL                  |       |
| max_questions          | int(11) unsigned                  | NO   |     | 0                     |       |
| max_updates            | int(11) unsigned                  | NO   |     | 0                     |       |
| max_connections        | int(11) unsigned                  | NO   |     | 0                     |       |
| max_user_connections   | int(11) unsigned                  | NO   |     | 0                     |       |
| plugin                 | char(64)                          | NO   |     | mysql_native_password |       |
| authentication_string  | text                              | YES  |     | NULL                  |       |
| password_expired       | enum('N','Y')                     | NO   |     | N                     |       |
| password_last_changed  | timestamp                         | YES  |     | NULL                  |       |
| password_lifetime      | smallint(5) unsigned              | YES  |     | NULL                  |       |
| account_locked         | enum('N','Y')                     | NO   |     | N                     |       |
+------------------------+-----------------------------------+------+-----+-----------------------+-------+
45 rows in set (0.03 sec)

檢視user中的已存在的使用者和主機

mysql> select Host, User from user;
+-----------+------------------+
| Host      | User             |
+-----------+------------------+
| localhost | debian-sys-maint |
| localhost | mysql.session    |
| localhost | mysql.sys        |
| localhost | root             |
+-----------+------------------+
4 rows in set (0.00 sec)

接著我們新增一個自己的賬戶使用

mysql> CREATE USER '填使用者名稱'@'localhost' IDENTIFIED BY '填密碼';
Query OK, 0 rows affected (0.04 sec)

再次檢視user表

mysql> select Host, User from user;
+-----------+------------------+
| Host      | User             |
+-----------+------------------+
| localhost | ailumiyana       |
| localhost | debian-sys-maint |
| localhost | mysql.session    |
| localhost | mysql.sys        |
| localhost | root             |
+-----------+------------------+
5 rows in set (0.00 sec)

給新建的使用者新增許可權,重新整理許可權後, 檢視新增使用者的許可權是否已經加進去.

mysql> grant insert,select,delete,update,create,drop on *.* to [email protected]"localhost" identified by 'qwedsa';
Query OK, 0 rows affected, 1 warning (0.01 sec)

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

mysql> show grants for [email protected];
+---------------------------------------------------------------------------------------+
| Grants for [email protected]                                                       |
+---------------------------------------------------------------------------------------+
| GRANT SELECT, INSERT, UPDATE, DELETE, CREATE, DROP ON *.* TO 'ailumiyana'@'localhost' |
+---------------------------------------------------------------------------------------+
1 row in set (0.00 sec)

當然我們自己用,當然設定所有許可權,更為便捷,那麼可以改成這樣子
all privileges 表示所有許可權.

mysql> grant all privileges on *.* to [email protected]"localhost" identified by 'qwedsa';
Query OK, 0 rows affected, 1 warning (0.00 sec)

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

mysql> show grants for [email protected];
+---------------------------------------------------------+
| Grants for [email protected]                         |
+---------------------------------------------------------+
| GRANT ALL PRIVILEGES ON *.* TO 'ailumiyana'@'localhost' |
+---------------------------------------------------------+
1 row in set (0.00 sec)

退出,重啟服務.

mysql> exit
Bye
[email protected]:~/Git_Project/Go_Test$ service mysql restart
==== AUTHENTICATING FOR org.freedesktop.systemd1.manage-units ===
Authentication is required to restart 'mysql.service'.
Authenticating as: ailumiyana,,, (ailumiyana)
Password: 
==== AUTHENTICATION COMPLETE ===

這樣新使用者就新增進去了,也配置了適當的許可權,接下來用golang簡單測試一下。

使用go-sql-driver驅動測試Mysql

先在mysql中建立一個表

mysql> create table user_info(
    -> id int(4) not null primary key auto_increment,
    -> name char(20) not null);
Query OK, 0 rows affected (0.29 sec)

插入兩個資料到user_info表中,然後查詢此表。

package main

import (
    "github.com/astaxie/beego/logs"
    "database/sql"
    _ "github.com/go-sql-driver/mysql"
)

func main() {
    logs.Debug("main()")
    db, err := sql.Open("mysql", "ailumiyana:[email protected](127.0.0.1:3306)/mysql")
    if err != nil {
      logs.Error("sql Open() err", err)
    }

    stmt, err := db.Prepare("Insert user_info set id=?,name=?")
    if err != nil {
      logs.Error("sql Prepare() err", err)
    }

    stmt.Exec(1, "sola")
    stmt.Exec(2, "ailumiyana")

    rows, err :=db.Query("SELECT * FROM user_info")
    if err != nil {
      logs.Error("sql Query() err", err)
    }

    for rows.Next() {
        var uid int
        var username string

        err = rows.Scan(&uid, &username)
        if err != nil {
          logs.Error("sql rows.Scan() err", err)
        }
        logs.Debug(uid, username)
    }

}

其中sql.Open中的 第二個從引數是DSN格式資料 :
DSN(資料來源名稱)
資料來源名稱有一種常見的格式,例如PEAR DB使用的它,但是沒有型別字首(可選部分用方括號標記):
Alt text

DSN的完整形式:
Alt text

另外此例用了beego 的日誌模組,和go-sql-driver驅動,使用前需要先用go get 下載。
go get可以根據要求和實際情況從網際網路上下載或更新指定的程式碼包及其依賴包,並對它們進行編譯和安裝。在上面這個示例中,我們從著名的程式碼託管站點Github上下載了一個專案(或稱程式碼包),並安裝到了環境變數GOPATH中包含的第一個工作區中。

結果

[email protected]:~/Git_Project/Go_Test$ go run mysql.go 
2019/01/07 14:38:08.438 [D]  main()
2019/01/07 14:38:08.443 [D]  1 sola
2019/01/07 14:38:08.443 [D]  2 ailumiyana
mysql> select * from user_info
    -> ;
+----+-------------+
| id | name        |
+----+-------------+
|  1 | sola        |
|  2 | ailumiyana  |
+----+-------------+
2 rows in set (0.02 sec)