mysql基础

MYSQL

1、库的管理

1、 登陆mysql:mysql -uroot
-p密码

2、 查看所有的库,show
databases;

3、 创建一个属于自己的库:create
database 库名 character set utf8;

4、 查看创建库的语句(查看字符集):show create
database 库名;

5、 查看当前所在库:
select database();

6、 切换库:use 库名;

7、 查看库中的表:show
tables;

8、 删除库:drop
database 库名

2、表的管理

               1、创建表(别忘了选择库,也可以指定字符集)

                           create table 表名(

                         字段名,数据类型,

                        name char(10),
                        age int,

                        字段名,数据类型

                        )character set utf8;

               2、查看创建表的语句(字符集,存储引擎)

                         show create table 表名;

               3、查看表结构

                        desc  表名;

               4、删除表

  drop  table 表名;(可以删多个)

3、查询(select)

     1、select *

from 表名 where 条件;

     1、插入(insert)一条或多条记录

                                 insert

into 表名 values(值1),(值2),(值······);

4、数据类型:

     1、数值类型:

               tinyint  微小整型(一个字节) 0~255

                                 1、有符号(signed默认):-128~127

                                 2、无符号(unsigned):0~255

               smallint   小整型(两个字节)

               bigint   极大整型(8个字节

     2、字符类型

               varchar:变长

     3、枚举类型

               enum

     4、日期时间类型

5、表字段操作:

     1、添加字段(add)

               alter

table 表名 add 字段名 数据类型;

     3、删除字段  (drop)

               alter

table 表名 drop 字段名;

     4、修改字段数据类型(modify)

               alter  table 表名 modify 字段名  新数据类型;

修改表名(rename)

               alter  table 表名  rename 新表名;

5、修改字段名(charge)

               alter  table 表名  charge 

原字段名
新字段名 数据类型;

6、表记录操作

     1、删除表记录(delete)

               1\delete

from 表名 where 条件;

               2、注意:一定要加where条件, 不加where条件全部删除表记录

     2、更新表记录(update)

               1、update 表名  set  字段名1=值1,字段2=值2 where 条件;否则全改

               ##

一定要加where条件 不然全部更新

 2、范围内比较:

                   1、between 值1 and 值2

                   2、in(值1,值2···)

                   3、not in (值1,值2)

          3、练习(控制优先级用小括号)

                   1、查找攻击值在100~200之间的蜀国英雄信息

          select * from

sanguo where (gongji between 100 and 200) and country=“蜀国”

                   2、查找蜀国和吴国以外的国家的英雄的信息

select * from sanguo where country not in(“蜀国”,“吴国”) and
sex = “女”;

                   3\查找id为1,3或5的蜀国英雄和貂蝉的信息

select * from sanguo where (id in(1,3,5) and country=“蜀国”) or
name=“貂蝉”

 3、匹配空和非空

          1、空:is null

          2、非空:is not  null

          3、练习:       

                   1、查找姓名为 Null的蜀国男英雄信息

select * from sanguo where name is null and coutry =“蜀国” and sex=“男”;

                   2、查找姓名为“”的英雄信息

select * from sanguo where name = “”;

                   3、在所有蜀国英雄中查找攻击力大于150的并且名字不为NULL

的英雄的姓名、攻击值和国家

select name,gongji,country from sanguo where country=“蜀国” and
gongji>150 and name is not null;

          4、查找魏蜀两国英雄中攻击力小于200并且防御力小于80的英雄信息

select * from sanguo where country in(“魏国”,“蜀国”) and
gongji<200 and fangyu<80;

 1、_:一个下划线匹配单个字符                      

                   2、%:匹配0到多个字符

          3、练习:

          select name from

sanguo where name like “%”; (名字最少两个字符的)

          select name from

sanguo where name like “%”;(0到多个字符)空值不是字符

order by:给查询结果进行排序

 将所有英雄按防御值从高到低排序

select * from
sanguo order by fangyu DESC;

          avg(字段名):求该字段的平均值

                   sum(字段名):求和

                   max(字段名):最大值

                   min(字段名);最小值

                   count(字段名):统计该字段记录的个数

 所有英雄中攻击力最大值

          select

max(gongji) from sanguo;

7、表字段、表记录操作

          表字段(alter

table 表名) 表记录

增: add
insert into 表名

删: drop delete
from 表名

改:
modify update
表名 set ···

查:
desc 表名; select

  • from 表名····

       查询操作:
    

1、distinct:不显示字段的重复值(去重)

      select distinct 字段名1,字段2  from 表名;

     2、示例:

               1、表中都有哪些国家

               select

distinct country from sanguo;

     1、查询时显示所有英雄攻击力翻倍

               select

id,name,gongji*2 from sanguo;

     select

id,name,gongji*2 as new from sanguo

约束:1、默认约束(default)

                        插入记录时不给该字段赋值,则使用默认值

                        sex

enum(“M”,“F”,“S”) default “S”;

               2、非空约束(not

null)

                        不允许该字段的值为null

                        id

int not null,

3、索引

     1、定义:

        对数据库中表的一列或多列的值进行排序的一种结构

2、优点:

加快数据的检索(查找)速度

     3、缺点:

      1、当你对表中数据更新时,索引也需要动态的维护,降低维护的速度

             2、索引需要占用物理存储空间

2、普通索引的创建 KEY标志:MUL

     1、创建表时创建

       1、create table t1(

               ...,....,

               index(name),

               index(id) );

       2、已有表中创建

               create index

索引名 on 表名(字段名);

       3、查看索引

              1、desc 表名;--->KEY

标志为MUL

               2、show index

from 表名\G;

       4、删除index

               drop index 索引名 on 表名;

drop index id on t2;(删除id的索引)

2、唯一索引(unique KEY标志:UNI

     2、创建

               1、创建表时创建

                 unique(phnumber),

                 unique(cardnumber)

3、主键索引(primary key)&& 自增长属性(auto_increment)KEY标志:PRI

       1、使用规则

              1、在一张表中只能有一个字段为主键     

            2、约束:字段值不允许重复,也不能为NULL

            3、KEY标志:PRI

            4、通常设置记录编号字段

id,能够唯一锁定一条记录

       2、创建       

               1、创建表时

                 1、id int primary key

auto_increment,(把id设置为主键)

     2、已有表

                        alter

table 表名 add primary key(id);

alter table 表名 modify id int auto_increment;(在已有表中添加自增长属性)

     alter table 表名 auto_increment =10000;

3、删除主键

1、先删除自增长属性(modify)

alter table 表名 modify id int;

2、删除主键

alter table 表名 drop primary key;

alter table t4 modify

8、表的复制

1、语法格式

     create

table 表名 select …from 表名 where 条件;

1、外键(foreign key)

     1、定义:让当前表的字段值在另一张表的范围内去选择

     3、使用规则

               1、主表,从表字段数据类型要一致

               2、主表,被参考字段一定要是主键

     2、语法格式

       1、foreign key(参考字段名)

       2、references(参照) 主表(被参考字段名)

       3、on delete 级联动作

       4、on update 级联动作

1、数据备份(mysqldump,在Linux终端操作)

1、命令格式

     mysqldump

-u用户名 -p 原库名 > ***.sql

mysqldump -uroot -p student >
student.sql

       2、源库名的表示方式

     --all-databases                                备份所有库

     库名                                           备份一个库

     -B

库1 库2··(空格) 备份多个库

     库名 表1表2···        备份多张表

     3、练习:

     1、备份所有的库,放到mydata目录下: All.sql

     mysqldump -uroot -p --all-databases > All.sql

     2、备份student库中的sheng\city\xain三张表,studentscx.sql

mysqldump -uroot -p student sheng city xian

studentscx.sql

     3、备份MOSHOU和student 两个库,md.sql

mysqldump -uroot -p -B MOSHOU student > md.sql;

、数据恢复:

1、命令格式(Linux 终端)

     mysql -u用户名 -p 目标库名 <(重定向输出)

***.sql

mydata$ mysql -uroot -p db4 < student.sql;

2、从所有库备份All.sql
中恢复某一个库

mysql -u用户名 -p --one-database 目标库名< All.sql

mysql -uroot -p --one-database db4 <
All.sql

3、示例:

     1、在db4.sheng添加一条记录

insert into sheng values(null,300000,“黑龙江省”);

select * from sheng where s_name=“黑龙江省”);

     2、在db4库,新建一张表t888

create table t888(id int);

     3、从student.sql恢复db4库

mysql -uroot -p db4 < student.sql;

1、在恢复库时,如果恢复到原库会将表中数据覆盖,新增表不会删除

2、恢复库时,如果库不存在,则必须先创建空库

4、事务和事务回滚

1、定义:一件事从开始发生到结束的整个过程

2、作用:确保数据的一致性

     2、事务的操作

       1、开启事务

               mysql>

begin; |
transactions;(作用一样)

               mysql>SQL

命令 …

                        ##

此时autocommit 被禁用##

       2、终止事务

               mysql>

commit; | rollback;

2、pymysql使用流程

     1、建立数据库连接对象(db

= pymysql.connect(“root”.

     2、创建游标对象 cur(操作数据库的对象)

     3、游标对象:cur.execute("insert

into sheng…;")

     4、提交到数据库执行:db.commit()

     5、关闭游标对象

sur.close()

     6、关闭数据库连接对象

db.close()fgye4y64ef6yg7gg6t54vbyhcxvbhhftrd

import pymysql

‘’‘1.创建数据库连接对象’’’

db =
pymysql.connect(host=“localhost”,

                 user="root",

password=“123456”,

                 database="db4",

charset=“utf8”)

2.利用db创建游标对象

cursor = db.cursor()

3.利用cursor的execute方法执行SQL命令

cursor.execute("insert
into sheng values\

          (30,400000,'吉林省');")

4.提交到数据库执行

db.commit()

print(“ok”)

5.关闭游标对象

cursor.close()

6.断开数据库连接

db.close()

     3、connect连接对象

       1、db=pymysql.connect(参数列表)

               1、host:主机地址

               2、user:用户名

               3、password:密码

               4、database: 库

               5、charset:编码方式,推荐utf8

               6、port:端口(3306默认)

       2、db(数据库连接对象)的方法

               1、db.close():断开与数据库连接

               2、db.commit():提交到数据库执行

               3、db.cursor():创建游标对象,用来执行SQL命令

               4、db.rollback():

回滚

from pymysql import
connect

class MysqlHelp:

def __init__(self, database,

host=“localhost”,

             user="root",

password=“123456”,

             charset="utf8",

port=3306):

    self.database = database

    self.host = host

    self.user = user

    self.password = password

    self.charset = charset

    self.port = port



# 连接数据库方法

def open(self):

    #

创建一个数据库连接对象conn

    self.conn = connect(host=self.host,

user=self.user,

password=self.password,

database=self.database,

charset=self.charset,

                        port=self.port)

    # 创建游标对象cur

    self.cur = self.conn.cursor()



# 关闭方法

def close(self):

    self.cur.close()

    self.conn.close()



# 执行SQL 语句  增删改

def workOn(self, sql, L=[]):

    self.open()  # 自身调用

创建

    try:

        self.cur.execute(sql, L)

        self.conn.commit()

        print("ok")

    except Exception as e:

        self.conn.rollback()

        print("Failed", e)

    self.close()



# getAll查询方法

def getAll(self, sql, L=[]):

    self.open()

    self.cur.execute(sql, L)

    print("ok")

    result = self.cur.fetchall()

    self.close()

    return result

if name ==
main”:

# 测试

mysql = MysqlHelp("db4")

# sql_insert = "insert into

sheng(s_name) values(‘河北省’’)"

# mysql.workOn(sql_insert)

sql_select = "select * from

sheng;"

result = mysql.getAll(sql_select)

print(result)



     5、锁

       1、目的:解决客户端并发访问的冲突问题
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值