可視化工具Navicat的使用/pymysql模塊的使用

一.可視化工具Navicat的使用

1.官網下載:http://www.navicat.com/en/products/navicat-for-mysql

2.網盤下載:http://pan.baidu.com/s/1bpo5maj

3.須要掌握的基本操做:

  View Code

PS:在生產環境中操做MySQL數據庫仍是推薦使用命令工具mysql,但咱們本身開發測試時,可使用可視化工具Navicat,以圖形界面的形式操做MySQL數據庫python

二.pymysql模塊的使用

1.pymysql的下載和使用

以前咱們都是經過MySQL自帶的命令行客戶端mysql來操做數據庫,那如何在python程序中操做數據庫吶?這就用到了pymysql模塊,該模塊的本質就是一個套接字客戶端軟件,使用前須要事先安裝mysql

(1).pymysql模塊的下載

pip3 install pymysql

(2).pymysql的使用(數據庫和數據都已存在)

  View Code

2.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()方法: 在數據庫裏增,刪,改的時候,必需要進行提交,不然插入的數據不生效sql

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示例中,在獲取行數據的時候,能夠理解開始的時候,有一個行指針指着第一行的上方,獲取一行,它就向下移動一行,因此當行指針到最後一行的時候,就不能再獲取到行的內容,因此咱們可使用以下方法來移動行指針:ide

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/工具

相關文章
相關標籤/搜索