MySQL notes

MySQL 备忘,已经用到的一些命令,方式信马游缰。一句话总结:那些我用到的MySQL语句。

MySQL

shell登录,‘-u’用户‘root’;‘-p’需要密码。
1
$ mysql -u root -p

New db

  • Create database
1
create database db_name;
  • Add user
1
2
insert into mysql.user(Host,User,Password) \
values("localhost","user_name",password("user_password"));
  • Show user
1
select user,host,password from mysql.user;
  • Add permission
1
2
3
grant all privileges on db_name.* to \
user_name@localhost identified by 'user_password';
flush privileges;
  • Show permission
1
show grants for user_name@'localhost';
  • Alter character (utf-8)
1
alter database db_name default character set = utf8;
  • Recommend create
1
CREATE database db_name DEFAULT CHARACTER SET utf8;

Other

  • foreign_key_checks
一对好基友
1
2
3
set foreign_key_checks = 0;
$_do_some_command;
set foreign_key_checks = 1;
  • show databases
1
show databases;
  • use databases
1
use db_name;
  • truncate table
清空表中所有内容,结构不变化:
1
truncate table table_name;
  • drop table
销毁表,结构不复存在:
1
drop table table_name;
  • update
1
update db_name.table_name set column_name = new_value where id>0 and your_where

id>0 我是被那个safe update逼的。

End: 本文仅总结了我用到的一些语句。

注:代码命令中含有_的,很多时候是需要你修改的。但也有不是的,如set xx_xx = 0,你需要修改0 or 1

and & or

Python 的bool运算 and & or,但运算结果不是单纯的False或者True,无疑结果是对的。一句话总结:用最少的运算,保留更多的信息,保证正确的结果。

Documentation

Operation Result Notes
x or y if x is false, then y, else x 运算是短路的
x and y if x is false, then x, else y 运算是短路的

关于短路

print None and None[0]没有报错,正常打印出None。(None[0]会报TypeError错)

bool ? x : y运算

由于python的bool运算保留了更多信息,所以可以实现上述三目运算。

三目运算

三目运算是这样的,可是存在一个误区! bool and x or y

误区,当x为假时,永远返回y。

修正上述误区:((test and [x]) or [y])[0]采用了x为假时,[x]为真(避免上述误区),然后[0]索引求值。

还有种简洁的写法:(y, x)[bool] 其中x,y是反的,用bool索引求值。

上面涉及了两个值,网上还有三个或更多值的,我就不多少了,也不建议去搜。ugly

技巧VS陷阱

我认为,这个既算不上技巧,也不能称为陷阱。

python实现三目运算还是用x if bool else y,从看着到结果都比较顺眼。当然适当的使用and & or保留值的特性也是可以的,主要是你要明白你写的是什么。

写代码,自己要明白,还要让看的人明白。

(看的人也要知道自己看的是python)