MySQL— pymysql模塊(防止sql注入),可視化軟件Navicat

一.Pymysqlhtml

import pymysql
#python2.X 中是 mysqldb 和 pythonmysql 用法是如出一轍的
#pymysql能夠假裝成上面這兩個模塊

user = input('username: ')
pwd = input('password: ')

#鏈接數據庫
conn = pymysql.connect(host='localhost',user='root',password='gkx321',database='db222')
cursor = conn.cursor() #相似文件句柄。 好比conn是打開了一個櫃子,cursor就是咱們拿東西的手
# cursor = conn.cursor(cursor=pymysql.cursors.DictCursor) #設置爲字典格式,fetch的時候能夠顯示字段名,以字典形式

#注意之後絕對不要這麼拼接
# sql =  "select * from userinfo where username='%s' and password = '%s' "%(user,pwd)
# username: uu' or 1=1 --
# password: gkx
# (1, 'gkx', 'gkx123')
# 登錄成功

#正確方式
sql =  "select * from userinfo where username = %s and password = %s "

#三種方式 元組,列表,字典
# cursor.execute(sql)
cursor.execute(sql,(user,pwd))  #執行語句  ,末尾加不加逗號都行
#r = cursor.execute(sql,(user,pwd))  #有個返回值,表示受影響的行數

# cursor.execute(sql,[user,pwd])

# sql =  "select * from userinfo where username = %(u)s and password = %(p)s "
# cursor.execute(sql,{'u':user,'p':pwd})

ret = cursor.fetchone() #fetchone相似 readline 運行一次,只讀取一行。
print(ret)

cursor.close()
conn.close()
if ret:
    print('登錄成功')
else:
    print('登錄失敗')
pymysql初識
#總結
    #查詢須要 fetchone
    #更新和insert 須要 conn.commit()
    #create drop alter 只要 cursor.execute()
import pymysql

conn = pymysql.connect(host='localhost',user='root',password='gkx321',database='db222')
# cursor = conn.cursor() #相似文件句柄。 好比conn是打開了一個櫃子,cursor就是咱們拿東西的手
cursor = conn.cursor(cursor=pymysql.cursors.DictCursor) #設置爲字典類型的 cursor
'''
#增長 刪除 改
# user = 'ccc'
# pwd = 'ccc123'
sql =  "insert into userinfo(username,password) values(%s,%s)"
# cursor.execute(sql,(user,pwd,))
cursor.executemany(sql,[('ww','ww123'),('aaa','aaa123')]) #增長多行,只適合insert時候用
# r = cursor.execute(sql,(user,pwd,)) #返回值,受影響的行數
conn.commit() #增刪改 三種操做必定要 commit 不提交數據庫不知道要修改
for 循環中 能夠 所有execute後,再進行一次 commit
'''

#
sql = "select * from userinfo"
cursor.execute(sql)

# 既然fetchone像文件中的readline,那麼就有相似 tell和seek的語句:
cursor.scroll(2,mode='relative')  #根據當前位置,相對移動 .2表示從當前位置,選擇下下行,天然1就是選擇下一行了
cursor.scroll(2,mode='absolute')  #根據絕對位置移動       2表示從第1行日後的2行,即表示選擇第3行

#能夠經過設置cursor,來讓fetchone顯示的時候,帶上字段名,以字典形式
ret = cursor.fetchone() #只有查詢的時候才須要
print(ret)
ret = cursor.fetchone()
print(ret)
ret = cursor.fetchall()
print(ret)
#
# ret1 = cursor.fetchall()  #返回一個元組,每條數據又是一個元組
# print(ret1)

#要注意的是,儘可能仍是要用sql語句操做,由於好比fetchall/fetchmany 會把全部數據放到內存中來,好比10萬條數據,那麼是至關佔內存的
#仍是建議用 sql中的 limit 分頁
# ret1 = cursor.fetchall()
# ret2 = cursor.fetchmany(3)


cursor.close()
conn.close()
pymysql—增刪改查
#新插入數據的自增id  cursor.lastrowid
import pymysql

conn = pymysql.connect(host='localhost',user='root',password='gkx321',database='db222')
cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)

sql = "insert into userinfo(username,password) values('ddd','ddd123')"
cursor.execute(sql)
print(cursor.lastrowid) #
#獲取插入數據的自增id
#那若是是插入多行呢,也只獲取最後一行的 自增id,因此有須要外鍵的話,只能一個個插入再獲取
conn.commit()

cursor.close()
conn.close()
新插入數據的自增id
import pymysql
import sys
conn = pymysql.connect(host='localhost',user='root',password='gkx321',database='db222')
cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)


def select(sql,cursor,conn):
    ret = cursor.execute(sql)
    print('受影響行數爲%s行'%ret)
    ret2 = cursor.fetchall()
    return ret2

def drop(sql,cursor,conn):
    ret = cursor.execute(sql)
    return '\033[34m操做成功\033[0m'

def change(sql,cursor,conn):
    ret = cursor.execute(sql)
    conn.commit()
    if ret:
        return '\033[34m受影響行數爲%s行\033[0m'%ret
    else:
        print('輸入不正確')
        return False

# def quit(sql, cursor, conn):
#     print('退出了')
#     exit()
def login(cursor,conn):
    count = 0
    while count<3:
        user = input('用戶名:')
        pwd = input('密碼:')
        sql = "select * from user where username=%s and password=%s"
        ret = cursor.execute(sql,(user,pwd))
        if ret:
            sql = "select * from u_g left join grant_info on u_g.g_id = grant_info.id left join user on u_g.u_id = user.id;"
            cursor.execute(sql)
            ret = cursor.fetchall()
            for line in ret:
                if line['username'] == user:
                    print('%s的權限是%s'%(line['username'],line['grant_lst']))
            return True
        else:
            print('用戶信息有誤')
            count += 1
    return False



def op():
    while True:
        menu = [('查詢','select'),
                ('增長','change'),
                ('新建表','drop'),
                ('刪除','drop'),
                ('更新','change'),
                ('退出','')
                ]
        for index,item in enumerate(menu,1):
            if index < len(menu):
                print('%s:%s'%(index,item[0]),end='  ')
            else:
                print('%s:%s'%(index,item[0]))
        try:
            choi = int(input('選擇操做序號:'))
            if choi == 6:
                print('\033[31m已選擇退出\033[0m')
                break
            print('\033[32m進行%s操做\033[0m' % menu[choi - 1][0])
        except:
            print('\033[31m選擇有誤,請輸入序號\033[0m')
            continue
        print('\033[34m輸入sql語句,或者按q返回\033[0m')
        sql = input('輸入sql命令>>:')
        if sql == 'q':
            continue

        try:
            func = getattr(sys.modules[__name__], menu[choi - 1][1])
            ret = func(sql, cursor, conn)
            if choi != 1:
                print(ret)
            else:
                for index,item in enumerate(ret):
                    print(item)
        except:
            print('\033[31m語法有誤,從新輸入\033[0m')


    cursor.close()
    conn.close()


ret = login(cursor, conn)
if ret:
    op()
pymysql做業1

pymysql做業1:簡單實現用pymysql進行數據庫管理python

import random
import pymysql

conn = pymysql.connect(host='localhost',user='root',password='gkx321',database='db300w',charset='utf8')
cursor = conn.cursor()

#
# name = 'alex'
# emai = 'email'
# for i in range(0,2000000):
#     i = str(i)
#     gender = random.choice(['男', '女'])
#     sql = "insert into userinfo(name,email,gender) values(%s,%s,gender)"
#     cursor.execute(sql % (name+i,emai+i))
# conn.commit()
#
# cursor.close()
# conn.close()

name = 'alex'
emai = 'email'
for i in range(3,3000001):
    gender = random.choice(['', ''])
    sql = " update userinfo set gender='%s' where id =%s;"% (gender,i)
    cursor.execute(sql)
conn.commit()

cursor.close()
conn.close()

#sql 拼接的時候,若是 %s 不加單引號,那麼sql語句裏也不會有單引號
pymysql做業2

pymysql做業2:用pymysql向表格插入300萬條數據mysql

# ===>要先問清楚,要求是什麼:公司開發一個項目,假設100天,可能有70天在明確需求
# 1. 基於角色的權限管理
# 2. 明確需求分析


# 基於角色的權限管理
#
# 用戶信息
    # id username     pwd     role_id
    # 1   alex     123123      1
    # 2   eric     123123      1
#
# 權限
    # 1    訂單管理
    # 2    用戶劵
    # 3    Bug管理
# ....
#
# 角色表:
    # 1    IT部門員工
    # 2    諮詢員工
    # 3    IT主管
#
# 角色權限管理
   #角色   #權限
    # 1     1
    # 1     2
    # 3     1
    # 3     2
    # 3     3

#那若是一個用戶有多個角色呢,能夠再多一個表 角色和用戶關係表
做業心得

要先問清楚,要求是什麼:公司開發一個項目,假設100天,可能有70天在明確需求sql

import pymysql

conn = pymysql.connect(host='localhost',user='root',password='gkx321',database='sql_homework',charset='utf8')
cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)

cursor.callproc('p3',(12,2)) #n1是12,無所謂n2是多少,不影響
ret = cursor.fetchall()
print(ret)

#out的值要這麼獲取,固定寫法
cursor.execute('select @_p3_0,@_p3_1') #能夠只寫一個 0獲取n1,1獲取n2
ret = cursor.fetchall()
print(ret)

'''
爲何格式是這樣呢,由於pymysql內部幫咱們作了這樣子的操做
set @ _p3_0 = 12
set @ _p3_1 = 2
call p3( @ _p3_0,@_p3_1)
select @ _p3_0,@_p3_1
'''

# cursor.execute('select * from teacher')
# ret = cursor.fetchall()
# print(ret)

cursor.close()
conn.close()
Pymysql-存儲過程的操做
# http://www.runoob.com/mysql/mysql-sql-injection.html
# https://www.cnblogs.com/sdya/p/4568548.html

# sql =  "select * from userinfo where username='%s' and password = '%s' "%(user,pwd)
#若是咱們這麼拼接字符串
# 當 %s 傳入爲  uu' or 1=1 -- 那麼sql語句變爲

# sql =  "select * from userinfo where username='uu' or 1=1 -- ' and password = '%s' "%(user,pwd) (-- 爲sql中的註釋符號)
# 從而讓sql變得不安全,能夠隨便登錄

具體見 上面例子中,《pymysql初識》
mysql注入

 

 

二.navicat是MySQL其中一個可視化軟件數據庫

#·······建議仍是用終端使用MySQL·······

#經過如下2步才能用 8.0登錄 navicat:
# mysql加密規則  https://www.cnblogs.com/atuotuo/p/9402132.html
#  ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY 'gkx321';
                    # 把mysql 8.0加密規則 從caching_sha2_password 更改成 mysql_native_password
#  Update user set host='%' where user='root';
# select user,host,plugin from user

#咱們用navicat這個IDE,主要仍是爲了學習過程當中,存儲和查看命令
#生產過程當中必定不要用,會被鄙視。
'''
#1.轉儲數據庫文件:
    #對着db右鍵,能夠把數據庫的結構和數據導出
    #導入的話,直接新建查詢,把sql的文件粘貼進入,運行便可。

    #那在終端要怎麼備份呢?
        #用 mysqldump
        #備份:數據表結構和數據
            #打開cmd 輸入命令: mysqldump -u root db1 > db1.sql -p 回車輸入密碼便可
            #保存位置在 cmd行輸入時候的路徑,文件名爲 db1.sql
        #只備份:數據表結構:
            #mysqldump -u root -d db1 > db1.sql -p  #多了個  -d
    #那備份的怎麼導入呢?
        #首先建立一個數據庫 create database db_name;
        #命令: mysqldump -uroot -p密碼 db_name < 文件路徑
'''
navicat初識
D:\python-全棧九期\navicat12
安裝包
相關文章
相關標籤/搜索