Python操做mysql

Python操做mysql

pymysql

安裝: pip install pymysql
import pymysql
#鏈接數據庫的參數
conn=pymysql.connect(host='localhost',user='root',passward='',database='tt',charset='utf8')
#cursor=conn.cursor() #默認返回的值是元組類型
cursor=conn.cursor(cursor=pysql.cursors.DictCursor)#返回的值是字典類型
sql="select * from userinfo"
cursor.execute(sql)

#res=cursor.fetchall()  #取出全部的數據 返回的是列表套字典
#res=cursor.fetchone()  #取出一條數據 返回的是字典類型
res=cursor.fetchmany(12)  #指定獲取多少條數據 返回的是列表套字典
print(res) 

cursor.close()
conn.close()
# 運行結果:
[{'id': 1, 'name': 'zekai', 'depart_id': 1}, {'id': 2, 'name': 'xxx', 'depart_id': 2}, {'id': 3, 'name': 'zekai1', 'depart_id': 3}, {'id': 4, 'name': 'zekai2', 'depart_id': 4}, {'id': 5, 'name': 'zekai3', 'depart_id': 1}, {'id': 6, 'name': 'zekai4', 'depart_id': 2}]
sql注入問題

   import pymysql

user=input('輸入用戶名:').strip()
pwd=input('輸入密碼:').strip()

#接下來對用戶輸入的值進行校驗

#鏈接數據庫的參數
conn=pymysql.connect(host='localhost',user='root',passward='',database='tt',charset='utf8')
#cursor=conn.cursor() #默認返回的值是元組類型
cursor=conn.cursor(cursor=pysql.cursors.DictCursor)#返回的值是字典類型

sql="select * from user where name='%s' and passward='%s'" %(user,pwd)

cursor.execute(sql)

res=cursor.fetchall()  #取出全部的數據 返回的是列表套字典
print(res)

cursor.close()
conn.close()

id res:
    print('登陸成功!')
else:
    print('登陸失敗!')
    
    
# 運行結果:
輸入用戶名:liang ' or 1=1 #
輸入密碼:1999
[{'id': 1, 'name': 'engon1', 'passward': 123.0}, {'id': 2, 'name': 'engon2', 'passward': 456.0}, {'id': 3, 'name': 'engon3', 'passward': 789.0}]
登陸成功

以上是sql注入問題
產生的緣由:由於過於相信用戶輸入的內容,根本沒有作任何的檢驗

解決方法:
sql="select * from user where name=%s and passward=%s"
cursor.execute(sql,(user,pwd))


# 運行結果:
輸入用戶名:engon1
輸入密碼:123
1
登陸成功
解決的方法:
    sql = "select * from user where name=%s and password=%s"

    cursor.execute(sql, (user, pwd))

鏈接:
    ### 鏈接數據庫的參數
    conn = pymysql.connect(host='localhost',user='root',password='123qwe',database='test',charset='utf8')
    # cursor = conn.cursor() ### 默認返回的值是元祖類型
    cursor = conn.cursor(cursor=pymysql.cursors.DictCursor) ### 返回的值是字典類型 (*********)
查:
    fetchall() : 取出全部的數據 返回的是列表套字典
    fetchone() : 取出一條數據 返回的是字典
    fetchmany(size) : 取出size條數據 返回的是列表套字典

增:
    sql = "insert into user (name, password) values (%s,  %s)"

    # cursor.execute(sql, ('xxx', 'qwe'))  ### 新增一條數據

    data = [
        ('zekai1', 'qwe'),
        ('zekai2', 'qwe1'),
        ('zekai3', 'qwe2'),
        ('zekai4', 'qwe3'),
    ]
    cursor.executemany(sql, data)  ### 新增多條數據

    #### 加以下代碼
    conn.commit()
print(cursor.lastrowid)   ### 獲取最後一行的ID值

修:
    sql = "update user set name=%s where id=%s"

    cursor.execute(sql, ('dgsahdsa', 2))

    conn.commit()

    cursor.close()
    conn.close()

刪除:
    sql = "delete from user where id=%s"

    cursor.execute(sql, ('dgsahdsa', 2))

    conn.commit()

    cursor.close()
    conn.close()

3.索引mysql

爲啥使用索引以及索引的做用:

    使用索引就是爲了提升查詢效率的

類比:
    字典中的目錄

索引的本質:
    一個特殊的文件
索引的底層原理:

    B+樹

索引的種類:(**************************)

    主鍵索引: 加速查找 + 不能重複 + 不能爲空 primary key
    惟一索引: 加速查找 + 不能重複    unique(name)
    聯合惟一索引:unique(name, email)
            例子:
                zekai 123@qq.com
                zekai 123@qq.cmm

    普通索引: 加速查找   index (name)
    聯合索引: index (name, email)
索引的建立:

    主鍵索引:

        新增主鍵索引:
            create table xxx(
                id int auto_increment ,
                primary key(id)
            )

            alter table xxx change id id int auto_increment primary key;

            alter table t1 add primary key (id);

        刪除主鍵索引:
            mysql> alter table t1 drop primary key;
惟一索引:

        新增:
            1.
            create table t2(
                id int auto_increment primary key,
                name varchar(32) not null default '',
                unique u_name (name)
            )charset utf8

            2.
            CREATE  UNIQUE   INDEX  索引名 ON 表名 (字段名) ;
                create  unique index ix_name on t2(name);

            3.
            alter table t2 add unique index ix_name (name)

        刪除:
            alter table t2 drop index u_name;

    普通索引:

        新增:
            1.
            create table t3(
                id int auto_increment primary key,
                name varchar(32) not null default '',
                index u_name (name)
            )charset utf8

            2.
            CREATE  INDEX  索引名 ON 表名 (字段名) ;
                create   index ix_name on t3(name);

            3.
            alter table t3 add  index ix_name (name)

        刪除:
            alter table t3 drop index u_name;

    索引的優缺點:

        經過觀察 *.ibd文件可知:

            1.索引加快了查詢速度
            2.但加了索引以後,會佔用大量的磁盤空間
索引加的越多越好?

        不是

    不會命中索引的狀況:

        a. 不能在SQl語句中,進行四則運算, 會下降SQL的查詢效率

        b. 使用函數
            select * from tb1 where reverse(email) = 'zekai';
        c. 類型不一致
            若是列是字符串類型,傳入條件是必須用引號引發來,否則...
            select * from tb1 where email = 999;

        #排序條件爲索引,則select字段必須也是索引字段,不然沒法命中
        d. order by
            select name from s1 order by email desc;
            當根據索引排序時候,select查詢的字段若是不是索引,則速度仍然很慢

            select email from s1 order by email desc;
            特別的:若是對主鍵排序,則仍是速度很快:
                select * from tb1 order by nid desc;

        e. count(1)或count(列)代替count(*)在mysql中沒有差異了

        f. 組合索引最左前綴

            何時會建立聯合索引?

                根據公司的業務場景, 在最經常使用的幾列上添加索引

                select * from user where name='zekai' and email='zekai@qq.com';

                若是遇到上述業務狀況, 錯誤的作法:
                    index ix_name (name),
                    index ix_email(email)

                正確的作法:
                    index ix_name_email(name, email)
若是組合索引爲:ix_name_email (name,email) ************

            where name='zekai' and email='xxxx'       -- 命中索引

            where name='zekai'   -- 命中索引
            where email='zekai@qq.com'                -- 未命中索引

            例子:

                index (a,b,c,d)

                where a=2 and b=3 and c=4 and d=5   --->命中索引

                where a=2 and c=3 and d=4   ----> 未命中
1.查詢的時候查詢條件精確匹配索引的左邊‘連續’一列或幾列,則此列就能夠被用到。
2.順序不一樣也能夠被查詢到,會自動優化爲匹配聯合索引的順序;
3.大多狀況下,都應該儘可能擴展 已有的索引而不是建立新的索引。
g:
            explain

            mysql> explain select * from user where name='zekai' and email='zekai@qq.com'\G
            *************************** 1. row ***************************
                       id: 1
              select_type: SIMPLE
                    table: user
               partitions: NULL
                     type: ref       索引指向 all
            possible_keys: ix_name_email     可能用到的索引
                      key: ix_name_email     確實用到的索引
                  key_len: 214            索引長度
                      ref: const,const
                     rows: 1            掃描的長度
                 filtered: 100.00
                    Extra: Using index   使用到了索引
索引覆蓋:

            select id from user where id=2000;

慢查詢日誌:sql

慢查詢日誌:
    查看慢SQL的相關變量

        mysql> show variables like '%slow%'
            -> ;
        +---------------------------+-----------------------------------------------+
        | Variable_name             | Value                                         |
        +---------------------------+-----------------------------------------------+
        | log_slow_admin_statements | OFF                                           |
        | log_slow_slave_statements | OFF                                           |
        | slow_launch_time          | 2                                             |
        | slow_query_log            | OFF   ### 默認關閉慢SQl查詢日誌, on                                          |
        | slow_query_log_file       | D:\mysql-5.7.28\data\DESKTOP-910UNQE-slow.log | ## 慢SQL記錄的位置
        +---------------------------+-----------------------------------------------+
        5 rows in set, 1 warning (0.08 sec)

        mysql> show variables like '%long%';
        +----------------------------------------------------------+-----------+
        | Variable_name                                            | Value     |
        +----------------------------------------------------------+-----------+
        | long_query_time                                          | 10.000000 |

    配置慢SQL的變量:
        set global 變量名 = 值

        set global slow_query_log = on;

        set global slow_query_log_file="D:/mysql-5.7.28/data/myslow.log";

        set global long_query_time=1;
相關文章
相關標籤/搜索