天天看点

入门关系型数据库mysql(2)

一,sql的一些子句

1,having 和where 作用类似    ,   having 一般放在group by 后面

2,select * from student order by age asc(升序)

     select * from teacher order by age desc

3,分页  select * from student limit 0,4       (页数,每页条数)

二,sql 内置函数

学习函数可以用select 语句 在navicat查询里试验。实际使用中可以以子查询的方式返回一列

1, 字符串函数:

SELECT ASCII("a") #97               将一个字符转换成ascii码
                select char(97);   #a                将ascii码转为char(字母或数字)
           
select concat(12,34,'ab'); #1234ab 把字母或是数字拼接起来
  select length('abxd') # 4 返回一个字符串的长度
  select right("sssssa",3)
  SELECT substring("hhshadfljhas",2,5)  hshad
  select replace('abc123','123','def'); #abcdef
  lower("ABC ") #abc

   uper("abc") #ABC               

2,数学函数:

ceiling(2.3)#3   向上取整
  floor(2.3);        向下取整
  round()        四色五入 
  pow(x,y)           求x的y次幂
  rand()             随机数,值为0-1.0的浮点数
  mod(m,n)         求m除以n的余数,同运算符
           

3,时间函数:

now()  完整版时间
        current_date()
        current_time()
        select year('2016-12-21');   #2016
        year(date)返回    date的年份(范围在1000到9999)
           
  • month(date)返回date中的月份数值
  • day(date)返回    date中的日期数值
  • hour(time)返回     time的小时数(范围是0到23)
  • minute(time)返回 time的分钟数(范围是0到59)
  • second(time)返回ime的秒数(范围是0到59)
  • 日期格式化date_format(date,format),format参数可用的值如下
    • 获取年 %Y,返回4位的整数

      * 获取年 %y,返回2位的整数

      * 获取月 %m,值为1-12的整数

    • 获取日%d,返回整数

      * 获取时 %H,值为0-23的整数

      * 获取时 %h,值为1-12的整数

      * 获取分 %i,值为0-59的整数

      * 获取秒 %s,值为0-59的整数

 三,sql的增删改查

    1,增,插入:insert into 表名()valuses()

    2,删 : delete  from 表名 【where 条件】

   3, 改  :更新: update 表名 set 字段="字段值 " where id=11

    4,查: select  字段名 from 表名

     ****增和删对数据库的影响较小,再操作改和删的时候要特别小心

四,使用python操纵数据库

import pymysql                           #需要梯田安装pysql
conn=pymysql.connect(host='127.0.0.1',port=3306,user='root',password='123456',db='stu_sys',charset='utf8') #链接数据库的函数,
#如果数据库中有中文,需要加charset=“utf8”,否则中文不能成功显示
curser=conn.cursor()                     #建立游标,操作数据库
curser.execute("select * from student")  #执行sql语句
result=curser.fetchall()                 #提取查询结果
for item in result:
   print(item)                          #(1, '张三', datetime.date(2011, 1, 27), '1') 便利了一遍还是一个元组,于是又遍历了一遍呢
  for j in item:
        print(j,end=' ')
    print(' ')
curser.close()                          #关闭游标
conn.close()                            #断开连接