mysql之pymysql模組
阿新 • • 發佈:2019-01-11
import pymysql user = input('user>>>:').strip() pwd = input('password>>>:').strip() # 建立連線 conn = pymysql.connect( host='127.0.0.1', port=3306, user='root', password='112233', db='db8', charset='utf8' ) # 拿到遊標 cursor = conn.cursor() # 執行sql語句sql = 'select * from userinfo where user = "%s" and pwd="%s"' % (user, pwd) rows = cursor.execute(sql) cursor.close() conn.close() # 進行判斷 if rows: print('登陸成功') else: print('登陸失敗')
二
import pymysql user = input('user>>>:').strip() pwd = input('password>>>:').strip() # 建立連線 conn = pymysql.connect( host='127.0.0.1', port=3306, user='root', password='112233', db='db8', charset='utf8' ) # 拿到遊標 cursor = conn.cursor() # 執行sql語句 # sql = 'select * from userinfo where user = "%s" and pwd="%s"' % (user, pwd) # print(sql) ''' 方式一 # select * from userinfo where user = "egon" -- xxxxxx" and pwd="" # 在sql中 --之後的都代表註釋掉。所以等於只查 where user ="egon" 方式二 # select * from userinfo where user = "xxx" or 1=1 -- hahahaha" and pwd="" # select * from userinfo where user = "xxx" or 1=1 其實是執行了這個,1=1永遠成立''' # 防止sql注入的方法,過濾到非法操作 sql = 'select * from userinfo where user = %s and pwd= %s ' rows = cursor.execute(sql, (user, pwd)) # 將使用者密碼在這裡傳入,pymysql內建的功能就能幫助你過濾 cursor.close() conn.close() # 進行判斷 if rows: print('登陸成功') else: print('登陸失敗')
三、pymysql之增刪改查
# 1、增刪改 import pymysql # 建立連結 conn = pymysql.connect( host='127.0.0.1', port=3306, user='root', password='112233', db='db8', charset='utf8' ) # 拿遊標 cursor = conn.cursor() # 執行sql # 增、刪、改 sql = 'insert userinfo(user,pwd) values(%s,%s)' # 刪改把insert換成相應的關鍵字就行 # cursor.execute(sql,('wxx','123')) # rows = cursor.executemany(sql, [('yxx', '123'), ('egon1', '123'), ('egon2', '123')]) # 插入多條記錄 # print(rows) # 3 rows = cursor.executemany(sql,[('egon3','123'),('egon4','123'),('egon5','123')]) print(cursor.lastrowid) # 7 插入之前id走到哪了,在插入三條就是7、8、9 conn.commit() # 執行commit才會對資料庫進行操作 # 關閉遊標和連結 cursor.close() conn.close() # 2、查詢 import pymysql # 建立連結 conn = pymysql.connect( host='127.0.0.1', port=3306, user='root', password='112233', db='db8', charset='utf8' ) # 拿遊標 cursor = conn.cursor(pymysql.cursors.DictCursor) # 以字典的形式取出來 # 執行sql # 查詢 rows = cursor.execute('select * from userinfo;') # print(rows) 6 # print(cursor.fetchone()) # 取一行,直到取到沒有就顯示None # print(cursor.fetchone()) # print(cursor.fetchmany(5)) # 指定取幾行 # print(cursor.fetchall()) # 取全部 # cursor.scroll(3,'absolute') # 絕對位置 # print(cursor.fetchone()) # 第四條 print(cursor.fetchone()) cursor.scroll(2,mode='relative') # 基於當前的位置往後在跳兩個 print(cursor.fetchone()) # 4 ,如果用absolute就是3 # 關閉遊標和連結 cursor.close() conn.close()