使用Python操作MySQL
簡介
MySQL 因?yàn)槌杀镜土?,性能高的?yōu)點(diǎn)已經(jīng)被各大應(yīng)用所選擇使用。在絕大部分的 Web 項(xiàng)目中更是如此。
當(dāng)前主流的 Web 應(yīng)用基本都是都是基于 Spring 全家桶開發(fā),這也決定了其開發(fā)語言必定是 Java。但由于 Java JDBC 以及 Java 語言本身的特點(diǎn)。要使用 Java 代碼編輯一段用于維護(hù)數(shù)據(jù)庫的過程就顯得有點(diǎn)繁瑣(java語言需要顯式的編譯才能運(yùn)行)。
如果我們能使用一種直接編寫完就可以執(zhí)行(解釋執(zhí)行)的語言來編寫維護(hù)腳本,那我們不管是調(diào)試還是維護(hù)都會(huì)很方便。
好在 MySQL 提供了很多種語言實(shí)現(xiàn)的連接器,例如:Java, Python, JavaScript, C++, C#, C, PHP, ODBC等等。顯然,Python 和 JavaScript兩種語言可以滿足我們的上述需求。
另外,對(duì) Linux Shell 操作熟練者,依舊可以通過命令行的方式直接與 MySQL Client 交互來寫出完美的腳本。這里,我們主要使用 Python 語言來說明如何操作數(shù)據(jù)庫。關(guān)于其他的 語言的連接器可以從 MySQL Connectors and APIs 獲取。
Python連接器版本參考
| Connector/Python Version | MySQL Server Versions | Python Versions | Connector Status |
| 8.0 | 8.0, 5.7, 5.6, 5.5 | 3.9, 3.8, 3.7, 3.6, (2.7 and 3.5 before 8.0.24) | General Availability |
| 2.2 (continues as 8.0) | 5.7, 5.6, 5.5 | 3.5, 3.4, 2.7 | Developer Milestone, No releases |
| 2.1 | 5.7, 5.6, 5.5 | 3.5, 3.4, 2.7, 2.6 | General Availability |
| 2.0 | 5.7, 5.6, 5.5 | 3.5, 3.4, 2.7, 2.6 | GA, final release on 2016-10-26 |
| 1.2 | 5.7, 5.6, 5.5 (5.1, 5.0, 4.1) | 3.4, 3.3, 3.2, 3.1, 2.7, 2.6 | GA, final release on 2014-08-22 |
安裝
使用 pip 命令可以在任意操作系統(tǒng)安裝,命令如下:
shell> pip install mysql-connector-python如果上述命令不能安裝,可以在 Python Connector Download下載編譯好的二進(jìn)制安裝包安裝。
?Windows:下載 *.msi 文件后直接雙擊安裝即可?Other:其他安裝方式可參考 Installing Connector/Python from a Binary Distribution
連接數(shù)據(jù)庫
示例代碼1:
import mysql.connectorcnx = mysql.connector.connect(user='scott', password='password',host='127.0.0.1',database='employees')cnx.close()
示例代碼2:
from mysql.connector import (connection)cnx = connection.MySQLConnection(user='scott', password='password',host='127.0.0.1',database='employees')cnx.close()
連接過程中的異常處理:
import mysql.connectorfrom mysql.connector import errorcodetry:cnx = mysql.connector.connect(user='scott',database='employ')except mysql.connector.Error as err:if err.errno == errorcode.ER_ACCESS_DENIED_ERROR:print("Something is wrong with your user name or password")elif err.errno == errorcode.ER_BAD_DB_ERROR:print("Database does not exist")else:print(err)else:cnx.close()
插入數(shù)據(jù)
示例代碼:
from __future__ import print_functionfrom datetime import date, datetime, timedeltaimport mysql.connectorcnx = mysql.connector.connect(user='scott', database='employees')cursor = cnx.cursor()tomorrow = datetime.now().date() + timedelta(days=1)add_employee = ("INSERT INTO employees ""(first_name, last_name, hire_date, gender, birth_date) ""VALUES (%s, %s, %s, %s, %s)")add_salary = ("INSERT INTO salaries ""(emp_no, salary, from_date, to_date) ""VALUES (%(emp_no)s, %(salary)s, %(from_date)s, %(to_date)s)")data_employee = ('Geert', 'Vanderkelen', tomorrow, 'M', date(1977, 6, 14))# Insert new employeecursor.execute(add_employee, data_employee)emp_no = cursor.lastrowid# Insert salary informationdata_salary = {'emp_no': emp_no,'salary': 50000,'from_date': tomorrow,'to_date': date(9999, 1, 1),}cursor.execute(add_salary, data_salary)# Make sure data is committed to the databasecnx.commit()cursor.close()cnx.close()
查詢數(shù)據(jù)
示例代碼:
import mysql.connectorcnx = mysql.connector.connect(user='root', password='root',host='127.0.0.1',database='erp')cursor = cnx.cursor()query = "SELECT `id`, role_name FROM MEMBER_ROLES"cursor.execute(query)for line in cursor:print(line)cursor.execute(query)for (idx, roleName) in cursor:print("id = {}, role_name = {}".format(idx, roleName))query += " limit 1"cursor.execute(query)data = cursor.fetchone()print(data)print("id = {}, role_name = {}".format(data[0], data[1]))cursor.close()cnx.close()
以上代碼的輸出示例:
(1, '工區(qū)長')(2, '技術(shù)主管')(3, '技術(shù)員')(4, '試驗(yàn)員')(5, '測(cè)量員')id = 1, role_name = 工區(qū)長id = 2, role_name = 技術(shù)主管id = 3, role_name = 技術(shù)員id = 4, role_name = 試驗(yàn)員id = 5, role_name = 測(cè)量員(1, '工區(qū)長')id = 1, role_name = 工區(qū)長
其他操作
通過上面的示例我們可以看出來,其實(shí)所有SQL操作的核心代碼為 cursor.execute(sql) 。簡化代碼為:
import mysql.connectorcnx = mysql.connector.connect(user='root', password='root',host='127.0.0.1',database='erp')cursor = cnx.cursor()query = "SELECT col FROM TABLE"cursor.execute(query)cursor.close()cnx.close()
上例中的 query 即我們需要執(zhí)行的SQL語句,我們根據(jù)業(yè)務(wù)來拼接就可以。
原文:https://www.jeremysong.cn/cn/mysql-curd-in-python/
歡迎關(guān)注我的公眾號(hào)“須彌零一”,更多技術(shù)文章第一時(shí)間推送。
