天天看點

入門關系型資料庫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()                            #斷開連接配接