可視化工具Navicat的使用/pymysql模塊的使用
阿新 • • 發佈:2019-01-15
什麽 令行 b- 必須 mysql數據庫 gif userinfo strong delete
一.可視化工具Navicat的使用
1.官網下載:http://www.navicat.com/en/products/navicat-for-mysql
2.網盤下載:http://pan.baidu.com/s/1bpo5maj
3.需要掌握的基本操作:
View CodePS:在生產環境中操作MySQL數據庫還是推薦使用命令工具mysql,但我們自己開發測試時,可以使用可視化工具Navicat,以圖形界面的形式操作MySQL數據庫
二.pymysql模塊的使用
1.pymysql的下載和使用
之前我們都是通過MySQL自帶的命令行客戶端mysql來操作數據庫,那如何在python程序中操作數據庫吶?這就用到了pymysql模塊,該模塊的本質就是一個套接字客戶端軟件,使用前需要事先安裝
(1).pymysql模塊的下載
pip3 install pymysql
(2).pymysql的使用(數據庫和數據都已存在)
View Code2.execute()之sql註入
#最後那一個空格,在一條sql語句中如果select * from userinfor where username = "wahaha" -- asadsadf" and pwd = "" 則--之後的條件被註釋掉了(註意--後面還有一個空格) #1.sql註入之:用戶存在,繞過密碼 wahaha" -- 任意字符 #2.sql註入之:用戶不存在,繞過用戶與密碼 xxx" or 1=1 -- 任意字符
(1).解決方法:
#原來是我們自己對sql字符串進行拼接 #sql = "select * from userinfo where username=‘%s‘ and pwd=‘%s‘" %(user, pwd) #print(sql) #result = cursor.execute(sql) #該寫為(execute幫我們做好的字符串拼接,我們無需且一定不要再為%s加引號了) sql = "select * from userinfor where name = %s and password = %s" #註意%s需要去掉引號,因為pymysql會自動幫我們加上 result = cursor.execute(sql,[user,pwd]) #pymysql模塊自動幫我們解決sql註入的問題,只要我們按照pymysql的規矩來
3.增,刪,改: conn.commit()
commit()方法: 在數據庫裏增,刪,改的時候,必須要進行提交,否則插入的數據不生效
import pymysql #連接 conn = pymysql.connect(host = "localhost", port = 3306, user = "root", password = "", db = "db8", charset = "utf8") #創建遊標 cursor = conn.cursor() # #增: # sql = "insert into userinfor(name,pwd) values (%s,%s)" # ope_data = cursor.execute(sql,(user,pwd)) # # #同時插入多條數據 # # cursor.executemany(sql,[("乳娃娃","111"),("爽歪歪","222")]) # print(ope_data) # #刪 # sql = "delete from userinfor where id = 2" # ope_data = cursor.execute(sql) # print(ope_data) # #改 # user = input("輸入新的用戶名:") # sql = "update userinfor set name = %s where id = 4" # ope_data = cursor.execute(sql,user) # print(ope_data) #一定要記得commit conn.commit() #關閉遊標 cursor.close() #關閉連接 conn.close()
4.查:fetchone,fetchmany,fetchall
fetchone():獲取下一行數據,第一次為首行 fetchall():獲取所有行數據源 fetchmany(4):獲取4行數據
(1).表中內容
(2).使用fetchone():
View Code(3).使用fetchall():
View Code默認情況下,我們獲取到的返回值是一個元組,只能看到每行的數據,卻不知道沒列代表的是什麽,這個時候可以使用以下方式來返回字典,每行的數據都會生成一個字典:
#返回字典 #在實例化的時候,將屬性cursor設置為pymysql.cursors.DictCursor cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)
在fetchone示例中,在獲取行數據的時候,可以理解開始的時候,有一個行指針指著第一行的上方,獲取一行,它就向下移動一行,所以當行指針到最後一行的時候,就不能再獲取到行的內容,所以我們可以使用如下方法來移動行指針:
cursor.scroll(1,mode=‘relative‘) # 相對當前位置移動 cursor.scroll(2,mode=‘absolute‘) # 相對絕對位置移動 第一個值為移動的行數,整數為向下移動,負數為向上移動,mode指定了是相對當前位置移動,還是相對於首行移動View Code
(4).使用fetchmany():
import pymysql conn = pymysql.connect(host = "localhost", port = 3306, user = "root", password = "", db = "db8", charset = "utf8") cursor = conn.cursor(cursor = pymysql.cursors.DictCursor) sql = "select * from userinfor" cursor.execute(sql) #獲取兩條數據 rows = cursor.fetchmany(2) print(rows) #關閉遊標 cursor.close() #關閉連接 conn.close() # 結果: [{‘id‘: 1, ‘name‘: ‘wahaha‘, ‘pwd‘: ‘123‘}, {‘id‘: 2, ‘name‘: ‘冰紅茶‘, ‘pwd‘: ‘111‘}]View Code
給大家推薦一位博主,他寫的很認真:https://www.cnblogs.com/rixian/
可視化工具Navicat的使用/pymysql模塊的使用