简介

Gradle 是以 Groovy 语言为基础,面向 Java 应用为主,基于 DSL 语法的自动化构建工具。

如何自动化打包(含签名的)

步骤

1、将准备好的keystore签名文件放在根目录下;(目的是待会儿配置 build.gradle 文件时,可以直接通过指定路径引用)
2、在 module 级别的 build.gradle 中添加如下配置代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
android {
// ...
signingConfigs {
myConfig {
storeFile file("lyloou.keystore")
storePassword "lyloou"
keyAlias "lyloou"
keyPassword "lyloou"
}
}

buildTypes {
release {
signingConfig signingConfigs.myConfig
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}

3、执行gradle clean清理之前的自动生成文件;
4、执行gradle build开始生成文件;
5、在build/outputs/apk/文件夹中可以看到生成成功的 apk 文件;

注意事项

通过执行gradle build自动生成的文件包含:

  • [项目名]-debug-unaligned.apk:指的是调试模式,没有优化的 apk(可直接安装)
  • [项目名]-release-unsigned.apk:指的是没有签名的 apk(不可直接安装)
  • [项目名]-debug.apk:指的是已经签名过的调试版 apk;
  • [项目名]-release.apk:指的是已经签名过的发布版 apk;

扩展技巧

参考资料

如何根据环境自动选择 key 或其他配置信息

动态替换AndroidManifest.xml中的 key 信息

  1. AndroidManifest中添加占位符
1
<data android:scheme="${WECHATAPPID}" />
  1. build.gradle中的defaultConfig标签或者buildTypes的 debug 和 release 标签下定义具体 value
1
2
3
defaultConfig {
manifestPlaceholders = [WECHATAPPID: "wxea2xxxxxxxxxxxxxxx"]
}

或者

1
2
3
4
5
6
7
debug {
manifestPlaceholders = [WECHATAPPID: "wxea2xxxxxxxxxxxxxxx1"]
}

release {
manifestPlaceholders = [WECHATAPPID: "wxea2xxxxxxxxxxxxxxx2"]
}

通过BuildConfig定义值

在不同的环境中设置不同的值,这样在打包(测试环境或正式环境)的时候就会有不同的值。注意定义完成后,要重新编译下环境,这样才能在 BuildConfig.java 中生效;

1
2
3
4
5
6
7
debug {
buildConfigField "boolean", "TEST_ENV", "true"
}

release {
buildConfigField "boolean", "TEST_ENV", "false"
}

在代码中引用

1
public static final boolean TEST_ENV = BuildConfig.TEST_ENV;

在编译之前执行脚本

1
2
3
4
5
6
7
8
9
10
// 在 settings.gradle 最上方添加
def updateDependencies(){
def command = "sh install.sh"
exec {
executable "bash"
args "-c", command
}
}

updateDependencies()

电子书

https://github.com/futurice/android-best-practices

Android 开发最佳实践

Android Studio 使用艺术

Android Best Practices

牛人网址

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
// 《Android进阶之光》p214
public class Main {
private static String convertStreamToString(InputStream stream) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer sb = new StringBuffer();
String line;
while ((line = reader.readLine()) != null) {
sb.append(line).append("\n");
}
String response = sb.toString();
return response;
}

// https://stackoverflow.com/questions/43157/easy-way-to-write-contents-of-a-java-inputstream-to-an-outputstream
// http://commons.apache.org/proper/commons-io/apidocs/org/apache/commons/io/IOUtils.html
// http://commons.apache.org/proper/commons-io/download_io.cgi
public static void convertStreamToFile(InputStream in, File out) throws IOException {
FileOutputStream outStream = new FileOutputStream(out);
IOUtils.copy(in, outStream);
in.close();
outStream.close();
}

public static void main(String[] args) {
// 网络图片
InputStream stream = new URL("https://www.cnblogs.com/images/logo_small.gif").openStream();

convertStreamToFile(stream, new File("./java/cnblog_logo.png"));

// 网页
InputStream stream2 = new URL("https://www.cnblogs.com/").openStream();

convertStreamToFile(stream2, new File("./java/cnblog.html"));

// 本地文件
FileInputStream fileInputStream = new FileInputStream("./java/hi.txt");

convertStreamToFile(fileInputStream, new File("./java/hi2.txt"));

// 获取字符串
FileInputStream fileInputStream2 = new FileInputStream("./java/hi.txt");
String str = convertStreamToString(fileInputStream2);
System.out.println(str);
}
}

定时功能

1
2
3
4
5
6
7
8
ScheduledExecutorService service = Executors.newScheduledThreadPool(1);
service.schedule(new Runnable() {
@Override
public void run() {
System.out.println("Yeah, I'm late.");
service.shutdown();
}
}, 10, TimeUnit.SECONDS);

多线程调试

一次只打一个断点。

获取服务器时间

原理:通过获取链接的 Header 信息来获取时间。
注意:网络请求需要在多线程中执行

1
2
3
4
5
6
7
URL url = new URL("http://lyloou.com");
URLConnection uc = url.openConnection();// 获取连接对象
uc.connect();// 连接
long webTimeMillis = uc.getDate();
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.CHINA);
String formatWebTime = simpleDateFormat.format(new Date(webTimeMillis));
System.out.println(formatWebTime);

添加顺序的注释

参考资料:深入探索 Android 热修复技术原理 7.3Q.pdf p107

// %% Part 1. 创建了新对象;
// %% Part 2. 找到旧对象的引用;
// %% Part 3. 用新对象赋值给旧对象的引用;

对象转换成字符串

在不确定对象是否为空时,通过String.valueOf(object)的方法,
而不是直接调用:object.toString();方法

封装

当类似的代码多次出现的时候,就可以考虑将其封装起来。

日期、时间格式的转换

1
2
3
4
5
6
7
8
9
10
String strDate = "2017-05-09T14:28:32.974Z";
SimpleDateFormat inputFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SS'Z'");
SimpleDateFormat outputFormat = new SimpleDateFormat("yy/MM/dd HH:mm:ss");
try {
Date inputDate = inputFormat.parse(strDate);
String outputDate = outputFormat.format(inputDate);
System.out.println(outputDate);
} catch (ParseException e) {
e.printStackTrace();
}

打印出好看的list

1
System.out.println(Arrays.toString(list.toArray()));

HashMap 用来缓存对象

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
private static final Map<String, Object> objectsCache = new HashMap<>();

// put in
public void putIn(String key, Object obj) {
objectsCache.put(key, obj);
}

// get out
public Object getOut(String key, Object default) {
if(objectsCache.containsKey(key)) {
Object obj = objectsCache.get(key);
if(obj == null) {
objectsCache.put(key, default);
}
return obj;
} else {
objectsCache.put(key, default);
return default;
}
}

根据 class 将 object 对象转换成 class 的对象

1
2
3
MyClass mobj = MyClass.class.cast(obj);
// or
Object newObj = Class.forName(classname).cast(obj);

问题

每个不同的地区都有对应有不同时间戳吗?

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
//: 通过程序证明来时间戳只有一个;
public class TimeTest {

public static void main(String[] args) {
Calendar now = new GregorianCalendar();
System.out.println(TimeZone.getDefault());
System.out.println(now.getTime());
System.out.println(now.getTime().getTime());
System.out.println();

TimeZone.setDefault(TimeZone.getTimeZone("GMT+8"));
System.out.println(TimeZone.getDefault());
System.out.println(now.getTime());
System.out.println(now.getTime().getTime());
System.out.println();

TimeZone.setDefault(TimeZone.getTimeZone("GMT+0"));
System.out.println(TimeZone.getDefault());
System.out.println(now.getTime());
System.out.println(now.getTime().getTime());
System.out.println();

TimeZone.setDefault(TimeZone.getTimeZone("GMT+12"));
System.out.println(TimeZone.getDefault());
System.out.println(now.getTime());
System.out.println(now.getTime().getTime());
}
}
/*
sun.util.calendar.ZoneInfo[id="Asia/Shanghai",offset=28800000,dstSavings=0,useDaylight=false,transitions=19,lastRule=null]
Thu Aug 10 09:39:22 CST 2017
1502329162745

sun.util.calendar.ZoneInfo[id="GMT+08:00",offset=28800000,dstSavings=0,useDaylight=false,transitions=0,lastRule=null]
Thu Aug 10 09:39:22 GMT+08:00 2017
1502329162745

sun.util.calendar.ZoneInfo[id="GMT+00:00",offset=0,dstSavings=0,useDaylight=false,transitions=0,lastRule=null]
Thu Aug 10 01:39:22 GMT+00:00 2017
1502329162745

sun.util.calendar.ZoneInfo[id="GMT+12:00",offset=43200000,dstSavings=0,useDaylight=false,transitions=0,lastRule=null]
Thu Aug 10 13:39:22 GMT+12:00 2017
1502329162745
*///~

结论

只有一个时间戳;
时间戳在所有地方都是一样的,只不过是该时间戳对应不同的地区有不同的当地时间表示(而不是有每个地区都有一个不同的时间戳)。

java程序设计总是采用按值调用

方法参数有两种类型:

  • 基本数据类型(数字、布尔值)
  • 对象引用

在传递对象的时候,实际上传递的是对象的引用拷贝。
对象引用和引用拷贝指向的是同一个对象,
可以通过对象自身的方法修改自己。

java中方法参数的使用情况

  • 一个方法不能修改一个基本数据类型的参数(即数值型或布尔型)
  • 一个方法可以改变一个对象参数的状态。
  • 一个方法不能让对象参数引用一个新的对象。

参考资料

  • 《java核心技术卷1》第10版,p118

快捷键

  • 同时选中所有匹配的 Ctrl+Shift+L
  • 回退上一个光标操作 Ctrl+U
  • 移动到定义处:F12 (或者:win+alt+left click)
  • 找到所有的引用:Shift+F12

Snippets in Visual Studio Code

配置编辑器的显示语言(菜单、控制台等)

  1. Ctrl+Shift+P
  2. Cofingure Language
  3. https://code.visualstudio.com/docs/getstarted/locales

插件

setting.json

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
{
"editor.fontSize": 15,
"editor.fontFamily": "Fira Code, Monaco, Consolas, 'Courier New', monospace",
"editor.fontLigatures": true,
"files.autoGuessEncoding": true,
"java.errors.incompleteClasspath.severity": "ignore",
"window.menuBarVisibility": "default",
"workbench.activityBar.visible": true,
"terminal.integrated.shell.windows": "D:\\c\\git\\bin\\bash.exe",

"window.openFoldersInNewWindow": "on",
"files.autoSave": "afterDelay",
"files.autoSaveDelay": 2000,
"window.zoomLevel": 0,
"editor.minimap.enabled": false,
"workbench.editor.enablePreview": false,
// 控制编辑器是否在滚动时使用动画
"editor.smoothScrolling": true,
// 总是隐藏打开的文件
"explorer.openEditors.visible": 0,
"window.title": "${rootName}${separator}${activeEditorLong}",
"workbench.iconTheme": "vscode-icons",
"editor.accessibilitySupport": "off",
"files.eol": "\n",
"window.enableMenuBarMnemonics": false,
"[markdown]": {
"editor.quickSuggestions": true
},
"editor.tabCompletion": "on",
"vetur.format.defaultFormatter": {
"html": "prettier",
"css": "prettier",
"postcss": "prettier",
"scss": "prettier",
"less": "prettier",
"js": "prettier",
"ts": "prettier",
"stylus": "stylus-supremacy"
}
}

keybindings.json

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
// 将键绑定放入此文件中以覆盖默认值
[
// =======> 方向
// 上
{
"key": "alt+i",
"command": "cursorUp",
"when": "editorTextFocus"
},
// 下
{
"key": "alt+,",
"command": "cursorDown",
"when": "editorTextFocus"
},
// 左
{
"key": "alt+h",
"command": "cursorLeft",
"when": "editorTextFocus"
},
// 右
{
"key": "alt+l",
"command": "cursorRight",
"when": "editorTextFocus"
},
// 开始
{
"key": "alt+0",
"command": "cursorHome",
"when": "editorTextFocus"
},
// 结束
{
"key": "alt+4",
"command": "cursorEnd",
"when": "editorTextFocus"
},
// =======> 选择
// 选中-上
{
"key": "shift+alt+i",
"command": "cursorUpSelect",
"when": "editorTextFocus"
},
// 选中-下
{
"key": "shift+alt+,",
"command": "cursorDownSelect",
"when": "editorTextFocus"
},
// 选中-左
{
"key": "shift+alt+h",
"command": "cursorLeftSelect",
"when": "editorTextFocus"
},
// 选中-右
{
"key": "shift+alt+l",
"command": "cursorRightSelect",
"when": "editorTextFocus"
},
// 选中-开始
{
"key": "shift+alt+0",
"command": "cursorHomeSelect",
"when": "editorTextFocus"
},
// 选中-结束
{
"key": "shift+alt+4",
"command": "cursorEndSelect",
"when": "editorTextFocus"
},
// 选中-左(单词)
{
"key": "ctrl+shift+alt+h",
"command": "cursorWordStartLeftSelect",
"when": "editorTextFocus"
},
// 选中-右(单词)
{
"key": "ctrl+shift+alt+l",
"command": "cursorWordEndRightSelect",
"when": "editorTextFocus"
},
// 扩选
{
"key": "alt+w",
"command": "editor.action.smartSelect.grow",
"when": "editorTextFocus"
},
// 缩选
{
"key": "alt+shift+w",
"command": "editor.action.smartSelect.shrink",
"when": "editorTextFocus"
},
// =======> 编辑
// 复制
{
"key": "alt+c",
"command": "editor.action.clipboardCopyAction",
"when": "editorTextFocus"
},
// 粘贴
{
"key": "alt+v",
"command": "editor.action.clipboardPasteAction",
"when": "editorTextFocus && !editorReadonly"
},
// save
{
"key": "alt+s",
"command": "workbench.action.files.save"
},
// 删除
{
"key": "alt+'",
"command": "deleteRight",
"when": "editorTextFocus && !editorReadonly"
},
// =======> 导航
// 标签-左
{
"key": "alt+j",
"command": "workbench.action.previousEditor"
},
// 标签-右
{
"key": "alt+k",
"command": "workbench.action.nextEditor"
}
]

Snippets

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
{
// Place your snippets for markdown here. Each snippet is defined under a snippet name and has a prefix, body and
// description. The prefix is what is used to trigger the snippet and the body will be expanded and inserted. Possible variables are:
// $1, $2 for tab stops, $0 for the final cursor position, and ${1:label}, ${2:another} for placeholders. Placeholders with the
// same ids are connected.
// Example:
"Add hexo header": {
"prefix": "head",
"body": [
"---",
"title: ${1:undefined}",
"date: $CURRENT_YEAR-$CURRENT_MONTH-$CURRENT_DATE $CURRENT_HOUR:$CURRENT_MINUTE:$CURRENT_SECOND",
"toc: true",
"comments: true",
"tags:",
" - ${2:undefined}",
"---"
],
"description": "Add hexo header"
},
"Add hexo image url": {
"prefix": "img",
"body": [
"![${1:this is an image}](https://github.com/lyloou/img/raw/develop/z/${2:$CURRENT_YEAR$CURRENT_MONTH$CURRENT_DATE$CURRENT_HOUR$CURRENT_MINUTE$CURRENT_SECOND.png})"
],
"description": "Add hexo image url"
}
}

| ubuntu 下 atom 禁用 alt+key 调出菜单

打开 edit -> preference -> open config folder -> init.coffee, 添加

1
2
3
4
# Get rid of the alt-menu shortcuts
atom.menu.template.forEach (t) ->
t.label = t.label.replace("&", "")
atom.menu.update()

当光标移到到元素上,别处相同元素高亮显示

该功能默认是打开的,但是有时候莫名奇妙的会被关闭,这时候通过下面的方式可以启用该功能。

具体步骤是:
windows->preferences->java->editor->mark occurrences 勾选复选框

更改颜色:
window->preferences->General->editors->text Editor->Annotations
右边选择–>Occurrence

linux 安装 mariadb

1
lsb_release -a
  • 添加源
1
2
3
sudo apt-get install software-properties-common
sudo apt-key adv --recv-keys --keyserver hkp://keyserver.ubuntu.com:80 0xF1656F24C74CD1D8
sudo add-apt-repository 'deb [arch=amd64,arm64,ppc64el] http://mirrors.neusoft.edu.cn/mariadb/repo/10.4/ubuntu bionic main'
  • 更新和安装
1
2
sudo apt update
sudo apt install mariadb-server
  • 查看安装状态
1
systemctl status mariadb
  • 查看 mysql version
1
mysql -V

https://linuxize.com/post/how-to-install-mariadb-on-ubuntu-18-04/

uninstall mariadb

1
2
3
4
5
6
apt-get remove --purge mysql*
apt-get remove --purge mysql
apt-get remove --purge mariadb
apt-get remove --purge mariadb*
apt-get --purge remove mariadb-server
apt-get --purge remove python-software-properties

重置密码

How to reset a MySQL root password | Linuxize

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
systemctl stop mysql

sudo mysqld_safe --skip-grant-tables &

mysql -u root

FLUSH PRIVILEGES;
ALTER USER 'root'@'localhost' IDENTIFIED BY 'lyloou06';
-- SET PASSWORD FOR 'root'@'localhost' = PASSWORD('MY_NEW_PASSWORD');
UPDATE mysql.user SET Password=PASSWORD('rebate@2020') WHERE User='root';
FLUSH PRIVILEGES;

-- restart
mysqladmin -u root -p shutdown
sudo systemctl start mariadb

-- login again
mysql -u root -p

外网登录常见问题

Q: ERROR 2003 (HY000): Can’t connect to MySQL server on (111 “Connection refused”)
A: mysql 远程连接数据库报 111 错误 - ssj901217 的博客 - CSDN 博客

1
2
3
4
5
6
vi /etc/mysql/my.cnf
找到
[mysqld]
bind-address = 127.0.0.1
注释掉bind-address
重启 mysql, systemctl restart mysql;

Q: ERROR 1130 (HY000): Host is not allowed to connect to this MariaDB server
A: 解决 MySQL ERROR 1130 (HY000): Host ‘XXXX’ is not allowed to connect to this MySQL server - HJULKK 的专栏 - CSDN 博客

1
2
3
4
5
6
7
8
mysql -u root -p
use mysql;
update user set host = '%' where user = 'root';
flush privileges;
select host, user from user;
quit
-- 步骤2:重启mysql,
systemctl restart mysql;

Q: mysql - ERROR 1698 (28000): Access denied for user ‘root‘@’localhost’ - Stack Overflow
A: see below code

1
2
3
4
5
6
7
sudo service mysql restart
sudo mysql # logs in automatically into MariaDB
use mysql;
update user set plugin='' where user='your_user_name';
flush privileges;
exit;
sudo service mysql restart # restarts the mysql service

Centos7.3 安装 Mysql5.7 并修改初始密码_酷玩时刻-By Javen-CSDN 博客_centos7 修改 mysql 密码

linux 安装 mysql

1
2
3
sudo apt-get update
sudo apt-get install mysql-server
sudo mysql_secure_installation

https://www.digitalocean.com/community/tutorials/how-to-install-mysql-on-ubuntu-16-04?comment=53320
If it occurs error because of broken MySQL package on Ubuntu 16.04. Just do this trick

1
2
3
4
5
6
7
# Purge all MySQL packages
sudo apt purge mysql*
sudo rm -rf /var/lib/mysql
sudo rm -rf /etc/mysql

# Reinstall MySQL
sudo apt install mysql-server mysql-client

centos

CentOS 7 - 安装 MySQL 5.7-阿里云开发者社区

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
# 添加Mysql5.7仓库
sudo rpm -ivh https://dev.mysql.com/get/mysql57-community-release-el7-11.noarch.rpm

# 确认Mysql仓库成功添加
sudo yum repolist all | grep mysql | grep enabled
# 开始安装
sudo yum -y install mysql-community-server

# 启动Mysql
sudo systemctl start mysqld

# 系统启动时自动启动
sudo systemctl enable mysqld

# 查看启动状态
sudo systemctl status mysqld

# CentOS上的root默认密码可以在文件/var/log/mysqld.log找到,通过下面命令可以打印出来
cat /var/log/mysqld.log | grep -i 'temporary password'

# 执行下面命令进行安全设置,这个命令会进行设置root密码设置,移除匿名用户,禁止root用户远程连接等
mysql_secure_installation

解决:conflicts between attempted installs of MariaDB-common

1
2
yum shell
remove mariadb-libs

由于 5.7 版本在安装的时候就设置好了,不需要额外设置,但是 5.6 版本建议从安全角度完善下,运行官方脚本即可

设置 root 密码
禁止 root 账号远程登录
禁止匿名账号(anonymous)登录
删除测试库
是否确认修改

默认配置

  • 端口:3306

其它软件

  • mycli

参考资料:

新建用户

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
-- 创建用户
CREATE USER 'bob'@'%'
IDENTIFIED BY 'password';

-- 授权1
GRANT ALL
ON *.*
TO 'bob'@'%'
WITH GRANT OPTION;

-- 授权2
GRANT privileges on databasename.tablename TO 'username'@'host';

-- 修改密码
SET PASSWORD FOR 'bob'@'%' = PASSWORD('bob');

-- 刷新
flush privileges;

MySQL :: MySQL 8.0 Reference Manual :: 6.2.8 Adding Accounts, Assigning Privileges, and Dropping Accounts

networking - MySQL: creating a user that can connect from multiple hosts - Server Fault

1
2
3
4
5
6
7
8
mysql root@120.123.232.2:mysql> GRANT all PRIVILEGES ON *.* to 'root'@'localhost';
(1133, "Can't find any matching row in the user table")

mysql root@120.123.232.2:mysql> GRANT all PRIVILEGES ON *.* to 'root'@'localhost' IDENTIFIED by 'localhost';
Query OK, 0 rows affected
Time: 0.002s

grant all privileges on testDB.* to 'test'@'1.1.1.1'identified by 'pswd';

mac install mariadb

1
2
3
4
5
6
7
8
9
10
11
xcode-select –install
ruby -e “$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)”
brew doctor

brew update
brew info mariadb
brew install mariadb
mysql_install_db
mysql.server start
mysql_secure_installation
mysql -u root -p

mysql 创建数据库,添加用户,用户授权实操方法

https://www.jb51.net/article/172998.htm

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
--创建名称为“testdb”数据库,并设定编码集为utf8
CREATE DATABASE IF NOT EXISTS testdb DEFAULT CHARSET utf8 COLLATE utf8_general_ci;
CREATE DATABASE IF NOT EXISTS testdb DEFAULT CHARSET utf8mb4 COLLATE utf8mb4_general_ci;

--创建了一个名为:test 密码为:1234 的用户
create user 'test'@'localhost' identified by '1234';
create user 'rebate'@'%' identified by 'rebate1234';
-- 注意:
-- 此处的"localhost",是指该用户只能在本地登录,不能在另外一台机器上远程登录。如果想远程登录的话,将"localhost"改为"%",表示在任何一台电脑上都可以登录。也可以指定某台机器可以远程登录。

--查询用户
select user,host from mysql.user;

--删除用户“test”
drop user test@localhost ;
--若创建的用户允许任何电脑登陆,删除用户如下
drop user test@'%';


--方法1,密码实时更新;修改用户“test”的密码为“1122”
set password for test =password('1122');
--方法2,需要刷新;修改用户“test”的密码为“1234”
update mysql.user set password=password('1234') where user='test'
--刷新
flush privileges;


--授予用户test通过外网IP对数据库“testdb”的全部权限
grant all privileges on rebate.* to 'test'@'%' identified by '1234';
grant all on rebate.* to rebate@'%' identified by 'rebate1234';

--刷新权限
flush privileges;

--授予用户“test”通过外网IP对于该数据库“testdb”中表的创建、修改、删除权限,以及表数据的增删查改权限
grant create,alter,drop,select,insert,update,delete on testdb.* to test@'%';

GRANT process ON . TO 'test'@'%';
flush privileges;

--查看用户“test”
show grants for test;
show grants for rebate;

简易版本

1
2
3
4
5
6
7
8
9
10
CREATE DATABASE IF NOT EXISTS db_movie DEFAULT CHARSET utf8mb4 COLLATE utf8mb4_general_ci;
create user 'admin'@'%' identified by '123456';
grant all privileges on db_movie.* to 'admin'@'%' identified by '123456';
grant all on db_movie.* to 'admin'@'%' identified by '123456';

grant create,alter,drop,select,insert,update,delete on db_movie.* to 'admin'@'%';
GRANT process ON *.* TO 'admin'@'%' identified by '123456';
flush privileges;

show grants for db_movie;
0%