Python操作MySQL

來源:互聯網
上載者:User

標籤:local   strong   cut   --   pass   from   mysqldb   install   參數化   

本篇對於Python操作MySQL主要使用兩種方式:

  • 原生模組 pymsql
  • ORM架構 SQLAchemy
pymsql

pymsql是Python中操作MySQL的模組,其使用方法和MySQLdb幾乎相同。

下載安裝

pip3 install pymysql -i https://pypi.douban.com/simple

使用操作

1、執行SQL

import pymysqluser = input("username:")pwd = input("password:")
# 建立串連conn = pymysql.connect(host="localhost",user=‘root‘,password=‘‘,database="db666")# 建立遊標
cursor = conn.cursor()sql = "select * from userinfo where username=‘%s‘ and password=%s" %(user,pwd,)
# select * from userinfo where username=‘uu‘ or 1=1 -- ‘ and password=‘%s‘ #sql注入

# 執行SQL,並返回收影響行數
cursor.execute(sql)# 擷取第一行資料
result = cursor.fetchone()cursor.close()conn.close()if result: print(‘登入成功‘)else: print(‘登入失敗‘)

注意:存在中文的時候,串連需要添加charset=‘utf8‘,否則中文顯示亂碼。

擷取查詢資料

結論:excute執行SQL語句的時候,必須使用參數化的方式,否則必然產生SQL注入漏洞。

import pymysqluser = input("username:")pwd = input("password:")conn = pymysql.connect(host="localhost",user=‘root‘,password=‘‘,database="db666")cursor = conn.cursor()sql = "select * from userinfo where username=%s and password=%s"cursor.execute(sql,user,pwd)  #推薦這種方法,防止sql注入 
# cursor.execute(sql,[user,pwd])# cursor.execute(sql,{‘u‘:user,‘p‘:pwd})#查詢一行
result = cursor.fetchone()
#查詢全部
result = cursor.fetchall()
#查詢四行
result = cursor.fetchmany(4)
cursor.close()conn.close()if result: print(‘登入成功‘)else: print(‘登入失敗‘)

註:在fetch資料時按照順序進行,可以使用cursor.scroll(num,mode)來移動遊標位置,如:

  • cursor.scroll(1,mode=‘relative‘)  # 相對當前位置移動
  • cursor.scroll(2,mode=‘absolute‘) # 相對絕對位置移動
增加,刪,該
conn = pymysql.connect(host="localhost",user=‘root‘,password=‘‘,database="db666")cursor = conn.cursor()sql = "insert into userinfo(username,password) values(%s,%s)"# 插入多行資料r = cursor.executemany(sql,[(‘egon‘,‘sb‘),(‘laoyao‘,‘BS‘)])#  ******# 提交,不然無法儲存建立或者修改的資料conn.commit()cursor.close()conn.close()

fetch資料類型

  關於預設擷取的資料是元祖類型,如果想要或者字典類型的資料,即:

# 查conn = pymysql.connect(host="localhost",user=‘root‘,password=‘‘,database="db666")# 遊標設定為字典類型cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)sql = "select * from userinfo"cursor.execute(sql)cursor.scroll(1,mode=‘relative‘)  # 相對當前位置移動cursor.scroll(2,mode=‘absolute‘) # 相對絕對位置移動# 查詢一行result = cursor.fetchone()print(result)# 查詢全部result = cursor.fetchall()print(result)# 查詢4行result = cursor.fetchmany(4)print(result)cursor.close()conn.close()
擷取新建立資料自增ID
# 新插入資料的自增ID: cursor.lastrowidimport pymysqlconn = pymysql.connect(host="localhost",user=‘root‘,password=‘‘,database="db666")cursor = conn.cursor()sql = "insert into userinfo(username,password) values(‘asdfasdf‘,‘123123‘)"cursor.execute(sql)conn.commit()# 新插入資料的自增ID,插入多條時也是拿到最後一條的IDprint(cursor.lastrowid)cursor.close()conn.close()

 

Python操作MySQL

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.