PyMySQL操作mysql資料庫(py3必學)

來源:互聯網
上載者:User

標籤:incr   weight   語言   word   mysq   登入密碼   hal   密碼   password   

一,安裝PyMySQL

Python是程式設計語言,MySQL是資料庫,它們是兩種不同的技術;要想使Python操作MySQL資料庫需要使用驅動。這裡選用PyMySQL驅動。

安裝方式還是使用pip命令。

> pip install  PyMySQL

二,建立MySQL表

執行下面的SQL語句,建立一張users 表。

CREATE TABLE `users` (    `id` INT(11) NOT NULL AUTO_INCREMENT,    `email` VARCHAR(255) COLLATE utf8_bin NOT NULL,    `password` VARCHAR(255) COLLATE utf8_bin NOT NULL,    PRIMARY KEY (`id`)) ENGINE=INNODB DEFAULT CHARSET=utf8 COLLATE=utf8_binAUTO_INCREMENT=1 ;

 

三,Python操作MySQL

4.1插入資料:

import pymysql.cursors# 串連MySQL資料庫connection = pymysql.connect(host=‘127.0.0.1‘, port=3306, user=‘root‘, password=‘198876‘, db=‘guest‘, 
charset=‘utf8mb4‘, cursorclass=pymysql.cursors.DictCursor)# 通過cursor建立遊標cursor = connection.cursor()# 建立sql 語句,並執行sql = "INSERT INTO `users` (`email`, `password`) VALUES (‘[email protected]‘, ‘123456‘)"cursor.execute(sql)# 提交SQLconnection.commit()

  不管你使用的是什麼工具或庫,串連資料庫這一步必不可少。host為資料庫的主機IP地址,port為MySQL的預設連接埠號碼,user為資料的使用者名稱,password為資料庫的登入密碼,db為資料庫的名稱。

  cursor()方法建立資料庫遊標。

  execute()方法執行SQL語句。

  commit()將資料庫的操作真正的提交到資料。

 

4.2. 查詢資料

import pymysql.cursors# 串連MySQL資料庫connection = pymysql.connect(host=‘127.0.0.1‘, port=3306, user=‘root‘, password=‘198876‘, db=‘guest‘, charset=‘utf8mb4‘, cursorclass=pymysql.cursors.DictCursor)# 通過cursor建立遊標cursor = connection.cursor()# 執行資料查詢sql = "SELECT `id`, `password` FROM `users` WHERE `email`=‘[email protected]‘"cursor.execute(sql)#查詢資料庫單條資料result = cursor.fetchone()print(result)print("-----------華麗分割線------------")# 執行資料查詢sql = "SELECT `id`, `password` FROM `users`"cursor.execute(sql)#查詢資料庫多條資料result = cursor.fetchall()for data in result:    print(data)# 關閉資料連線connection.close()

   接下來的操作就是資料庫的查詢了。

  fetchone() 用於查詢單條資料。

  fetchall() 用於查詢多條資料。

  close() 最後不要忘記了關閉資料連線。

  運行結果:

{‘password‘: ‘123456‘, ‘id‘: 1}-----------華麗分割線------------{‘password‘: ‘123456‘, ‘id‘: 1}{‘password‘: ‘654321‘, ‘id‘: 2}

PyMySQL操作mysql資料庫(py3必學)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.