Python操作Mysql

來源:互聯網
上載者:User

標籤:多個   sqlachemy   python   cut   操作   port   scroll   關閉   mode   

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

  • 原生模組 pymsql
  • ORM架構 SQLAchemy
使用操作

1、執行sql

import pymysql#建立串連,連上資料庫conn = pymysql.connect(host = ‘localhost‘,port = 3306, user = ‘root‘, passwd = ‘123‘,db = ‘sqlexample‘, charset = ‘utf8‘)#建立遊標cursor = conn.cursor()#向表中插入資料cursor.execute(‘insert into class(caption) VALUES("四年一班")‘)#提交,不然無法儲存建立和修改的資料conn.commit()#關閉遊標cursor.close()#關閉資料庫連接conn.close()

返回受影響行數,修改多個值

#返回受影響行數#effect_row = cursor.execute(‘insert into class(caption) VALUES("四年二班")‘)#插入多個值用executemany,放在一個可迭代對象中effect_row = cursor.executemany(‘insert into student(name,pwd,age) VALUES(%s,%s,%s)‘,[(‘wang‘,‘123‘,12),(‘yang‘,‘123‘,20),(‘qiang‘,‘123‘,25)])print(effect_row)

 刪除資料

#刪除資料effect_row = cursor.executemany(‘delete from student where nid=%s‘,(3,4))

 

修改資料

effect_row = cursor.execute("update student set name=‘luxun‘ where nid=2")

 

返回結果

effect_row = cursor.execute(‘select * from student‘ )print(effect_row)#擷取查詢結果(全部)result = cursor.fetchall()#擷取結果中的幾項result = cursor.fetchmany(2)#一項一項擷取result = cursor.fetchone()print(result)

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

  • cursor.scroll(1,mode=‘relative‘)  # 相對當前位置移動
  • cursor.scroll(-1,mode=‘relative‘)  # 相對當前位置移動,向上
  • cursor.scroll(2,mode=‘absolute‘) # 相對絕對位置移動

 2、fetch資料類型

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

#遊標設定為字典類型cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)

 

 3、防止sql注入:

如果用以下字串拼接的方式,即使使用者名稱密碼不正確,也能夠登入:

sql = ‘select name,pwd from student where name ="%s" and pwd = "%s" ‘sql = sql % (‘luxun11" or 1=1 -- ‘,1234)   #正確使用者名稱密碼為(’luxun‘,123)effect_row = cursor.execute(sql)result = cursor.fetchone()print(result)

 

 4、擷取新建立資料自增ID

    使用cursor.lastrowid擷取,多個資料,擷取最後一個id

effect_row = cursor.executemany(‘insert into student(name,pwd,age) VALUES(%s,%s,%s)‘,[(‘wang‘,‘123‘,12),(‘yang‘,‘123‘,20),(‘qiang‘,‘123‘,25)])new_id = cursor.lastrowidprint(new_id)

 

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.