mysql

連接

啟動服務   net start mysql
停止服務   net stop mysql
連接服務器  mysql -uroot -proot
(標準  mysql -hlocalhost -P3306 -uroot -proot)
    mysql -h localhost -u root -p
    //如果不寫默認連接localhost
    mysql -uroot -p
    mysql -uroot -proot

查看連接數

show processlist

mysql查看最大允許的上傳數據

my.ini中
    max_allowed_packet=1M

數據庫操作

1.針對數據庫和表的操作
    創建 create
    查看 show  
    刪除 drop
    修改 alter
2.針對表中數據操作
    增加 create
    刪除 delete
    修改 update (更新)
    查詢 select

查看數據庫

show databases;
這三張表不能動
    information_schema
    performance_schema
    mysql

數據庫字符集

查看數據庫和編碼相關的變量
    show variables like 'character%';
修改客戶端字符集(這樣就可以插入中文了)只是當前dos有效
    set character_set_client=gbk;
修改客戶端輸出字符集(這樣在查詢時就可以顯示中文了)只是當前dos有效
    set character_set_results=gbk;
集中修改客戶端配置信息
    到安裝目錄下找到my.ini文件。
    修改:
        default-character-set = gbk
        服務重啟即可。

創建數據庫

創建一個javatest數據庫
    create database javatest;
創建一個使用utf-8字符集的mydb數據庫
    create database mydb character set utf8;
創建一個使用utf-8字符集,并帶校驗規則的mydb數據庫
    create database mydb character set utf8 collate utf8_general_ci;
使用某個數據庫
    use javatest;
刪除數據庫
    drop database javatest;
查看mydb數據庫的定義信息
    show create database mydb;
修改數據庫
    修改一個mydb數據庫的字符集為gbk
    alter database mydb character set gbk;
備份數據庫(要先退出數據庫)
    mysqldump -u用戶名 -p密碼 數據庫名稱 > 文件名.sql
    備份mydb數據庫到D盤下的a.sql中,(注意:沒有分號結尾)
    mysqldump -uroot -p123456 mydb > D:\a.sql
恢復數據庫(不要退出數據庫)
    注意:數據庫是無法恢復的,恢復的是數據庫中的表和數據
    1先創建mydb數據庫,名字必須相同。
    2使用mydb數據庫庫:use mydb;
    3恢復mydb數據庫:soure D:\a.sql   (注意:這個命令不能寫分號)
查看所有的表
    show tables;

字符集問題

建表時默認是UTF-8
而在windows下窗口是GBK
//windows 窗口給mysql的數據是GBK的
set names gbk;

創建一張表

創建一張表
    create table person(
      id int,
      name varchar(20),
      age int
    )
語法:
    create table 表名(
        列名 列類型 [約束] [默認值]
    )engine 引擎名 charset 字符集;
創建一張表
    create table employee(
      id int,             //整形
      name varchar(20),
      gender varchar(6),    //字符型
      birthday date,
      entry_day date,     //日期型
      job char(20),        //字符型
      salary float,         //小數型
      resume text        //這個是大文本
    );
查看employee表的定義信息
    show create table employee;
查看employee表結構
    desc employee;
        Field 列名
        Type 類型
        Null 是否可以空
        Key 是鍵嗎
        Default 默認值是什么
        Extra 額外說明
在employee表的基礎上增加一個image字段
    alert table employee add image blob;
修改employee表中的job列的長度。
    alert table employee modify job varchar(60);
刪除employee表中的gender列
    alert table employee drop gender;
修改employee表中的name列的名字為username
    alert table employee change name username;
修改表的字符集為utf-8
    alter table employee character set utf8;
把employee表名修改為users
    rename table employee to users;
刪除users表
    drop table users;
表的約束
    給表中的字段添加一些約束。
    create table a
    (
      id int unique(約束),
      name varchar(20) not null,
      userid int primary key
    );
    唯一約束:unique  表中這個字段的數據不能重復
    非空約束:not null 表中這個字段不能有空值
    主鍵約束:primary key  就等于非空+唯一
    增加主鍵約束
        alter table user add primary key(id);
    刪除主鍵約束
        alter table user drop primary key;
    建立聯合主鍵 (讓兩個字段合在一起變成主鍵)
        所有的主鍵不能為null,所有的主鍵加在一起不允許出現重復
        create table a(
          firstname varchar(20),
          lastname varchar(20),
          primary key(firstname,lastname)
        );
    定義主鍵自增長
        create table a(
            id int primary key auto_increment
        );
    外鍵約束
        作用:被參照的列不允許刪除,參照列必須寫被參照列存在值
        create table husband(
          id int primary key auto_increment,
          name varchar(20)
        );
        create table wife(
          id int primary key auto_increment,
          name varchar(20),
          husbandid int,
          constraint husbandid_FK foreign key(husbandid) references husband(id)  //這個就是在給 husbandid 添加外鍵約束
        );
    解除外鍵參照關系
        update wife set husbandid = null where name = 'xiaohong';

字段的類型

說明
    建表:就是聲明列的過程
    數據以文件的形式放在硬盤中(也有放在內存中)
    列:不同的類型占的空間不一樣
    列的原則:夠用又不浪費
分類
    整型
        tinyint    1個字節
        smallint   2個字節
        mediumint  3個字節
        int 4個字節
        bigint  8個字節
    浮點型
        float(M,D) 浮點型
        decimal(M,D) 定點型
    字符型
        char(M)
        varchar(M)
        text
    時間/日期型
        datetime 日期時間
        date 日期
        time 時間
        year 年
        時間戳 int類型保存Long值
    枚舉 
        enum
整型tinyint(M) unsigned zerofill
    M : 寬度(在0填充時才有意義)
    unsigned :無符號類型(非負)
    zerofill :0填充,(默認無符號) 
    注意:M必須要和zerofill一起使用,否則無效。
    tinyint 默認存儲值的范圍是 -128 ~ 127
    tinyint unsigned 存儲值的范圍是 0 ~ 255
    tinyint(M) zerofill 的數據庫默認是 tinyint(M) unsigned zerofill
        默認數據不夠M位在前邊補0
        只是顯示效果,不會影響數據的真正存儲。
    //增加一列
    alter table person add money int unsigned
    alter table person add money1 int unsigned not null default 0; 默認值是0
    //unsigned用法
    create table person(
        id int,
        name varchar(20),
        age tinyint, //存儲范圍是 -128 ~ 127
        money tinyint unsigned //存儲范圍是 0 ~ 255
    );
小數型float(M,D)/decimal(M,D)
    M:精度(總位數,不包含點)
    D:標度(小數位)
    注意:decimal 更加精確,就是往數據庫插入值時,會出現數據精確問題。
    舉例:
        float(6,2)  存儲值的范圍是 -9999.99 ~ 9999.99
        float(6,2) unsigned 存儲值的范圍是 0.00 ~ 9999.99
        create table goods(
            name varchar(20) default '',
            price float(6,2) default 0.0 //存儲值的范圍是  -9999.99 ~ 9999.99
        );
        //結果是1000.00 會進位
        insert into goods (name,price) values ('zhangsan',999.998);
字符型 char(M)/varchar(M)/text
    char(M) 定長字符串  0 ~ 255
        M 可容納的字符數
        如果存儲小于M個字符,實占M個字符
        如果末尾有空格,取出數據時空格將被清除。
        速度上快
    varchar(M) 變長字符串 0 ~ 65535
        M 可容納的字符數
        如果存儲小于M個字符,存入幾個實占幾個字符
    text 文本串 2W ~ 6W
        不能加默認值
    例子
        create table user(
            name char(4), //只能存儲4個字符
            firstname varchar(4),//可以存儲8個字符
            description text
        );
        insert into user(name,firstname,description) values ('中國','aaaa','aaaa');
時間/日期型 datetime/date/time/year/時間戳
    datetime 日期時間 典型格式:2017-08-29 22:09:30
        存儲范圍 1000-01-01 00:00:00 ~ 9999-12-31 23:59:59
    date 日期 典型格式 2017-08-29
        存儲范圍 1000-01-01 ~ 9999-12-31
    time 時間 典型格式 hh:mm:ss
        存儲范圍 -838:59:59 ~ 838:59:59
    year 年  1個字節 1901~2155 出錯時是0000年
        如果輸入2位 00-69 表示 2000-2069
                    70-99 表示 1970-1999
    時間戳
        用int類型來存儲時間戳,方便計算。
枚舉 enum
    create table user(
        gender enum('男','女') //只能存 男或者女
    );
    insert into user (gender) values ('男');

表中數據操作

增加(插入)
    insert into student (id,name,age) values (1,'張三',20);
        第一個括號中的是列 ,后一個括號中的是值,要一一對應
        加單引號的是字符串
    insert into 表名(列名) values(值);
        注意:
            1.列名可以省略,但是值必須要全部賦值。
    insert into user(id,name) values(1,'zhangsan');
    insert into user(id,name) values (1,'zhangsan'),values (2,'lisi');
    insert into users(id,name,gender,birthday,salary,entry_date,resume) values(1,'zhangsan','male','1988-12-3',1000,'2008-4-15','good boy');
修改表中數據
    update student set name='王五' where id=1;
    update 表名 set 列名=值,列名=值 where 列名=值;
    update user set name='zhangsan' where id=1;
    修改user表中每條數據的name字段為lisi
        update user set name = 'lisi';
    修改user表中名字為zhangsan的salary為3000
        update user set salary = 3000 where name = 'zhangsan';
    修改user表中名字為zhangsan的salary為3000和gender為female
        update user set salary = 3000,gender = 'female' where name = 'zhangsan';
    修改user表中名字為zhangsan的salary的值增加1000
        updat user set salary = salary + 1000 where name = 'zhangsan';
刪除數據
    刪除所有  
        delete from student;//一行一行的刪除
        truncate user; //先摧毀表,再創建表。(效率高)
    刪除某條數據
        delete from student where id = 1;
        delete from user where name = 'zhangsan';
    語法
        delete from 表名 where 列名=值;
        delete from user where id=2;
查詢數據
    說明
        select的5種子句
            where 條件查詢
                模糊查詢
            group by 分組
            having 篩選
            order by 排序
            limit 限制結果條件
        5個統計函數
          max 最大值
          min  最小值
          sum 求總和
          avg 求平均
          count 求總行數
    查看student表中所有數據
        select * from student;
        select * from goods;
    查看student表中所有學生的名字和英語成績
        select name,english from student;
        select goods_id,goods_name,shop_price from goods;
    查看student表中所有學生的名字和英語成績,并且去掉重復數據
        select distinct name,english from student;
    查看student表中所有學生的所有成績,并且在成績中+10分,然后顯示
        select name,english+10,chinese+10,math+10 from student;
    修改查出來的字段名字(起別名)并且as可以省略
        select name,english+10 as english,chinese+10 as chinese,math+10 as math from student;
    統計學生的總分
        select name,english+math+chinese as sum from student;
    查詢名字為lisi的學生成績
        select * from student where name = 'lisi';
        select * from student where id = 1;
        select * from goods where goods_id = 10;
        select * from goods where shop_price = 2000;
    查詢英語成績大于90分的同學
        select *from student where english > 90;
        select * from student where id > 1;
        select * from goods where goods_id > 10;
        select * from goods where shop_price > 2000;
    查詢總分大于200分的所有同學
        select *from student where english+chinese+math>200;
        select * from goods where shop_price-goods_price > 300;
    查詢商品價格大于等于2000的商品
        select * from goods where shop_price >= 2000;
    查詢商品價格小于2000的商品
        select * from goods where shop_price < 2000;
    查詢商品價格小于等于2000的商品
        select * from goods where shop_price <= 2000;
    查詢商品不等于2000的商品
        select * from goods where shop_price <> 2000;
    查詢英語分數在80-90之間的同學
        select * from student where english between 80 and 90;
        select * from goods where id between 2 and 5; 范圍是:[2,5]
    查詢數學分數為89,90,91的同學
        select * from student where math in (89,90,91);
        select * from goods where id in(4,5);
    查詢商品id不是4和5的商品
        select * from goods where id not in (4,5);
    查詢所有姓李的學生(% 通配任意字符)
        select * from student where name like '李%';
        select * from goods where goods_name like '諾基亞%';
    查詢所有姓李的,并且名字為兩個字的學生成績(_ 通配單個字符)
        select * from student where name like '李_';
    查詢數學分數>80,語文分數>80的同學
        select *from student where math > 80 and chinese > 80;
    查詢英語>80 或者 總分>200的同學
        select * from student where english>80 or chinese+math+english>200;
    排序-對數學成績排序后輸出
        select * from student order by math; //升序 asc 默認
        select * from student order by math desc;//降序
    排序-對總分排序后輸出,然后再按照從高到底的順序輸出
        select * from student order by english+chinese+math desc;
    排序-對姓李的學生成績排序輸出
        select * from student where name like '李%' order by math;
    統計記錄-統計一個班級共有多少學生
        select count(*) from student;//會對所有的學生統計,沒問題
        selct count(chinese) from student;//會對chinese非空的所有學生統計。
        select count(*) from goods;
    統計記錄-統計數學成績大于90的學生有多少個
        select count(*) from student where math>90;
    統計記錄-統計總分大于250的人數有多少
        select count(*) from student where english+chinese+math>250;
    統計一個班級數學總成績
        select sum(math) from student;
        select sum(goods_number) from goods;
    統計一個班級語文、英語、數學各科的總成績
        select sum(math),sum(chinese),sum(english) from student;
    統計一個班級語文、英語、數學的成績總和
        select sum(math+chinese+english) from student;
    統計一個班級語文成績的平均分
        select sum(chinese)/count(*) from student;
        select sum(chinese)/count(chinese) from student;
    求一個班級數學平均分
        select avg(chinese) from student;
        select avg(price) from goods;
    求一個班級總分平均分
        select avg(chinese+math+chinese) from student;
    求班級的最高分(也就是一列數據中的最大值)
        select max(math) from student;
        select max(price) from goods;
    根據cat_id 分組,從每組中找出最貴的價格
        select cat_id,max(price) from goods group by cat_id;
    求班級的最低分(也就是一列數據中的最小值)
        select min(math) from student;
        select min(goods_id) from goods;
    查詢每類商品中最便宜的
        select cat_id,min(goods_price) from goods group by cat_id;
    在orders商品表中按照商品的名稱product分組
        select * from orders group by product;//每種名稱只顯示一次
        select *,count(*) from orders group by product;//每種名稱只顯示一次,并且顯示每組有多少個。
        select *,count(*),count(price) from orders group by product;//每種名稱只顯示一次,顯示每組有多少個,并且顯示每組的總和。
    顯示商品總價大于100的商品(注意:having只能跟在group by 后邊)    
        select *,count(*),sum(price) from orders group by product having sum(price) > 100;
    查詢每類商品中的平均價格
        select cat_id,avg(goods_price) from goods group by cat_id;
    查詢每類商品的商品種類
        select cat_id,count(*) from goods group by cat_id;
    查詢本店每個商品比市場價格低多少
        select goods_id,goods_name,market_price-goods_price from goods;
    查詢每類商品下積壓的貨款
        select cat_id,sum(shop_price * goods_number) from goods group by cat_id;
    給列起別名
        select cat_id,sum(shop_price * goods_number) as hk from goods group by cat_id;
        select cat_id,sum(shop_price * goods_number) hk from goods group by cat_id;
    查詢本店每個商品比市場價格低多少。并且把大于200的選出
        select goods_id,goods_name,market_price-goods_price as sheng from goods having sheng market_price-goods_price > 200;
    查詢本店每個商品比市場價格低多少。并且把第3類商品的大于200的選出
        select goods_id,goods_name,market_price-goods_price as sheng where goods_id = 3 from goods having sheng market_price-goods_price > 200;
    查詢積壓貨款超過2W元的分類,以及分類積壓的貨款
        select cat_id,goods_name,count(goods_price*goods_number) as hk from goods group by cat_id having hk > 20000;
    查詢該店積壓的貨款
        select sum(goods_price * goods_number) from goods;

存儲函數

無參返回字符串
    DELIMITER $$
    CREATE FUNCTION fun1() RETURNS CHAR(50)
    RETURN 'hello';
    $$
無參返回字符串
    DELIMITER $$
    CREATE FUNCTION fun4() RETURNS CHAR(50)
    BEGIN
    RETURN 'hello';
    END $$
無參返回int
    DELIMITER $$
    CREATE FUNCTION fun3() RETURNS INT
    RETURN 10;
    $$
無參返回int
    DELIMITER $$
    CREATE FUNCTION fun4() RETURNS INT
    BEGIN
    RETURN 10;
    END $$
有參返回int
    DELIMITER $$
    CREATE FUNCTION fun5(num int) RETURNS INT
    BEGIN
    RETURN num+10;
    END $$
    select fun5(5);
有參,有定義變量,并且初始化
    DELIMITER $$
    CREATE FUNCTION fun6(num INT) RETURNS INT
    BEGIN
        DECLARE num1 INT;
        SET num1 = 10;
        RETURN num+num1;
    END $$
    SELECT fun6(10);
有參返回int,并且定義變量,初始化變量從表中查取
    DELIMITER $$
    CREATE FUNCTION fun7(num INT) RETURNS INT
    BEGIN
        DECLARE num1 INT;
        SELECT COUNT(*) INTO num1 FROM goods;
        RETURN num+num1;
    END $$
    SELECT fun7(10);

存儲過程

無參無返回值
    delimiter $$
    create procedure one()
    begin
        select id,name,money from master;
    end $$
    call one();
有輸入參數無返回值
    delimiter $$
    create procedure two(tid int)
    begin
        select id,name,money from master where id = tid;
    end $$
    call two(2);
無參有返回值
    delimiter $$
    create procedure three(out tmoney int)
    begin
        select money into tmoney from master where id = 3;
    end $$
    set @a = '';
    call three(@a);
    select @a;
有輸入輸出參數
    delimiter $$
    create procedure four(in tid int,out tmoney int)
    begin
        select money into tmoney from master where id = tid;
    end $$
    set @a = '';
    call four(3,@a);
    select @a;
無參有輸出參數,有定義變量
    delimiter $$
    create procedure six(out tmoney int)
    begin
        declare tid int;
        set tid = 2;
        select money into tmoney from master where id = tid;
    end $$
    set @a = '';
    call six(@a);
    select @a;
查詢新聞總記錄數存儲過程
    create or replace procedure getNewsCount(out v_totalCount number) as
    begin
      select count(*) into v_totalCount from news;
    end;

重置數據庫密碼

1、編輯MySQL的配置文件:my.ini
    一般在MySQL安裝目錄下有my.ini即MySQL的配置文件。
    在此配置文件的最后添加如下一行:
    skip-grant-tables
    保存退出編輯。
2、然后重啟MySQL服務
    在命令行下執行:
    net stop MySQL
    net start MySQL
3、設置新的ROOT密碼
    然后再在命令行下執行:
    MySQL -u root -p MySQL或mysql -u root -p
    直接回車無需密碼即可進入數據庫了。
    此時,在命令行下執行 use mysql;
    現在我們執行如下語句把root密碼更新為:
    update user set password=PASSWORD("root") where user='root';
    (注意:此時不用使用mysqladmin -u root -p password '你的新密碼'這條命令修改密碼,因為'skip-grant-tables'配置,
    不信的話,你可以試用一下,它肯定會報如下所示的錯誤:
    F:\Documents and Settings\long>mysqladmin -u root -p password 'root'
    Enter password:
    Warning: single quotes were not trimmed from the password by your command
    line client, as you might have expected.
    mysqladmin:
    You cannot use 'password' command as mysqld runs
     with grant tables disabled (was started with --skip-grant-tables).
    Use: "mysqladmin flush-privileges password '*'" instead)
    exit 退出MySQL。
4、還原配置文件并重啟服務
    然后修改MySQL配置文件把剛才添加的那一行'skip-grant-tables'刪除。
    再次重起MySQL服務,密碼修改完畢。
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容