python學習-----9.17------補充子查詢、正則表示匹配、mysql用戶管理、pymysql模塊、

子查詢mysql

   將一個查詢的結果做爲下一次查詢的條件或原數據(又稱內查詢)正則表達式

   當你的需求一次查詢沒法知足需求時(一次select找不到你要的數據)就要用到子查詢sql

   子查詢能幹的是,多表聯查也能幹數據庫

 

正則表達式匹配安全

   關鍵字 regexp服務器

   select *from emp where name like "劉%"tcp

   select *from emp where name regxp "司.*光$";ide

 

mysql用戶管理fetch

   mysql是一個tcp服務器 用於操做服務器上的文件數據,編碼

   接受用戶端發送的指令,接受指令時須要考慮安全問題

   mysql把文件稱爲表 

   在mysql自帶的mysql數據庫中有4個表用於用戶管理

   分別是:優先級從高到低

        user ->db ->tables_priv -> columns_priv

 

 

create user  用戶名@"主機地址" identified by "密碼";
create user  scote@"127.0.0.1" identified by "123";
此處的主機地址 不是服務器地址 而是表示 這個帳戶能夠在那臺電腦上登陸
建立用戶的語句

 

        語法: grant [權限的名稱 select insert.... | all ] on 數據庫.表名  to 用戶名@主機地址;
        # 授予 scote 這個用戶全部權限 在全部數據庫全部表中
        grant all on *.* to scote@"localhost"; 能夠訪問 全部庫和表
        grant all on day41.* to scote@"localhost";  能夠訪問day41庫的全部表
        grant all on day41.stu to scote@"localhost"; 能夠訪問day41庫的stu表
        grant select(id,name),insert(id,name) on day41.stu to scote@"localhost";
                                                    僅能查看和添加 day41庫的stu表中的 id和name字段


        grant all on mydb1.* to testDBA@"%"  identified by "123";


    3.grant [權限的名稱 select insert.... | all ] on 數據庫.表名  to 用戶名@主機地址 with grant option;
        with grant option 這個用戶能夠將他有的權限授予別的帳戶
        特色: 若是受權時  用戶不存在 直接自動建立用戶
用戶受權的語句
       revoke 權限的名稱 on 數據庫.表名  from 用戶名@"主機名" ;
       revoke all on *.* from scote@"localhost";

       update mysql.user set  Grant_priv = "N" where user ="scote" and host = "localhost";

     *.刷新權限表
        flush privileges;
刪除權限
     drop user 用戶名@"主機地址";
刪除用戶

 

 

import pymysql

"""pymysql使用步驟
    核心類 Connect連接用  和Cursor讀寫用
    1.與數據庫服務器創建連接
    2.獲取遊標對象 (用於發送和接收數據)
    3.用遊標執行sql語句
    4.使用fetch方法來獲取執行的結果
    5.關閉連接  先關遊標 再關連接
    
    遊標的經常使用方法
    1.建立遊標  conn.cursor(指定查詢結果的數據類型)
    2.excute  執行sql
    3.fetchone(當sql只有一條記錄時)  many(sql有多條而且須要指定條數)  all(多條)
    4.scroll  用於修改遊標的當前位置
    
    
    注意: pymysql 默認不提交修改  可是注意(指的是對錶中記錄的操做不提交)  像刪庫 刪表 是沒法撤銷的
    
    
"""
# 建立連接獲得一個連接對象
conn = pymysql.Connect(
    host="127.0.0.1",    # 數據庫服務器主機地址
    user="root",  # 用戶名
    password="admin", # 密碼
    database="day42", #數據庫名稱
    port=3306, # 端口號 可選 整型
    charset="utf8" # 編碼  可選
)
# 獲取遊標對象  pymysql.cursors.DictCursor指定 返回的結果類型 爲字典  默認是元祖類型
cursor = conn.cursor(pymysql.cursors.DictCursor)

# 查詢數據
sql = "select *from emp"

# 執行sql  若是是select 語句返回的是 查詢的條數
res = cursor.execute(sql)
print(res)

# 獲取查詢的結果
# print(cursor.fetchall())
# print(cursor.fetchone())
# print(cursor.fetchone())
# print(cursor.fetchmany(1))
# print(cursor.fetchall())

# scroll
print(cursor.fetchone())
cursor.scroll(-1)
print(cursor.fetchall())


# 關閉連接
cursor.close()
conn.close()
pymysql模塊的使用

commit  提交修改

  由於pymysql模塊默認是啓用事務的,sql語句若是不提交 至關於沒有執行

roback   回滾,撤銷數據修改

相關文章
相關標籤/搜索