如何用命令行对mysql进行操作

(1)启动服务器
如果发现”Can’t connect to local MySQL server through socket…”,通常是因为MySQL服务器没有启用。

用命令行启动和关闭MySQL服务器:

1
2
sudo /usr/local/mysql/support-files/mysql.server start
sudo /usr/local/mysql/support-files/mysql.server stop

(2)修改root用户密码
方法1: 用SET PASSWORD命令

1
2
  mysql -u root
  mysql> SET PASSWORD FOR 'root'@'localhost' = PASSWORD('newpass');

方法2:用mysqladmin

1
  mysqladmin -u root password "newpass"

如果root已经设置过密码(123456),那么修改密码为abcdef的命令是:

1
mysqladmin -u root -p123456 password abcdef

注意:上述命令中参数-p不要和后面的密码分开写,要写在一起,不然会出错

方法3: 用UPDATE直接编辑user表

1
2
3
4
  mysql -u root
  mysql> use mysql;
  mysql> UPDATE user SET Password = PASSWORD('newpass') WHERE user = 'root';
  mysql> FLUSH PRIVILEGES;

在丢失root密码的时候,可以这样

1
2
3
4
  mysqld_safe --skip-grant-tables&
  mysql -u root mysql
  mysql> UPDATE user SET password=PASSWORD("new password") WHERE user='root';
  mysql> FLUSH PRIVILEGES;

(3)登录使用mysql

1
mysql -h localhost -u root -p