使用Python操作MySQL
简介
MySQL 因为成本低廉,性能高的优点已经被各大应用所选择使用。在绝大部分的 Web 项目中更是如此。
当前主流的 Web 应用基本都是都是基于 Spring 全家桶开发,这也决定了其开发语言必定是 Java。但由于 Java JDBC 以及 Java 语言本身的特点。要使用 Java 代码编辑一段用于维护数据库的过程就显得有点繁琐(java语言需要显式的编译才能运行)。
如果我们能使用一种直接编写完就可以执行(解释执行)的语言来编写维护脚本,那我们不管是调试还是维护都会很方便。
好在 MySQL 提供了很多种语言实现的连接器,例如:Java, Python, JavaScript, C++, C#, C, PHP, ODBC等等。显然,Python 和 JavaScript两种语言可以满足我们的上述需求。
另外,对 Linux Shell 操作熟练者,依旧可以通过命令行的方式直接与 MySQL Client 交互来写出完美的脚本。这里,我们主要使用 Python 语言来说明如何操作数据库。关于其他的 语言的连接器可以从 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 命令可以在任意操作系统安装,命令如下:
shell> pip install mysql-connector-python如果上述命令不能安装,可以在 Python Connector Download下载编译好的二进制安装包安装。
•Windows:下载 *.msi 文件后直接双击安装即可•Other:其他安装方式可参考 Installing Connector/Python from a Binary Distribution
连接数据库
示例代码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()
插入数据
示例代码:
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()
查询数据
示例代码:
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, '工区长')(2, '技术主管')(3, '技术员')(4, '试验员')(5, '测量员')id = 1, role_name = 工区长id = 2, role_name = 技术主管id = 3, role_name = 技术员id = 4, role_name = 试验员id = 5, role_name = 测量员(1, '工区长')id = 1, role_name = 工区长
其他操作
通过上面的示例我们可以看出来,其实所有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 即我们需要执行的SQL语句,我们根据业务来拼接就可以。
原文:https://www.jeremysong.cn/cn/mysql-curd-in-python/
欢迎关注我的公众号“须弥零一”,更多技术文章第一时间推送。
