如何使用 Python 对 MySQL 表的列执行算术运算?

pythonserver side programmingprogramming

顾名思义,算术运算用于执行加、​​减、除、乘或模等运算。

算术运算针对表中的数字数据进行运算。

语法

执行加法

SELECT op1+op2 FROM table_name

此处,op1 和 op2 是列名或数值。如果 op1 和 op2 是数值,则不需要 FROM 子句。

上述语法中的 + 可以用 -、*、%、/ 替换,以执行其他算术运算。

在 python 中使用 MySQL 在表中执行算术运算的步骤

  • 导入 MySQL 连接器

  • 使用 connect() 与连接器建立连接

  • 使用 cursor() 方法创建游标对象

  • 使用适当的 mysql 语句创建查询

  • 使用 execute() 方法执行 SQL 查询

  • 关闭连接

假设我们有以下名为"Sales"的表

+------------+---------+
| sale_price |    tax  |
+------------+---------+
|    1000    | 200     |
|    500     | 100     |
|    50      | 50      |
|    180     | 180     |
+------------+---------+

示例

我们需要将 sale_price 和 tax 两列的值相加来计算金额。

import mysql.connector
db=mysql.connector.connect(host="your host", user="your username", password="your
password",database="database_name")

cursor=db.cursor()

query="SELECT sale_price,tax, concat(sale_price+tax) AS amount FROM Sales"
cursor.execute(query)

rows=cursor.fetchall()

for row in rows:
   print(row)

db.close()

输出

( ‘sale_price’ , ‘tax’ , ‘amount’ )
(1000,200,1200)
(500,100,600)
(100,50,150)
(700,180,880)

对表格中的两列进行加法运算,同样,可以根据需要进行其他算术运算。


相关文章