MySQL 数据库查询与数据操作:使用 ORDER BY 排序和 DELETE 删除记录

编程入门 行业动态 更新时间:2024-10-24 22:31:07

MySQL <a href=https://www.elefans.com/category/jswz/34/1771047.html style=数据库查询与数据操作:使用 ORDER BY 排序和 DELETE 删除记录"/>

MySQL 数据库查询与数据操作:使用 ORDER BY 排序和 DELETE 删除记录

使用 ORDER BY 进行排序

使用 ORDER BY 语句按升序或降序对结果进行排序。

ORDER BY 关键字默认按升序排序。要按降序排序结果,使用 DESC 关键字。

示例按名称按字母顺序排序结果:

import mysql.connectormydb = mysql.connector.connect(host="localhost",user="yourusername",password="yourpassword",database="mydatabase"
)mycursor = mydb.cursor()sql = "SELECT * FROM customers ORDER BY name"mycursor.execute(sql)myresult = mycursor.fetchall()for x in myresult:print(x)

ORDER BY DESC

使用 DESC 关键字以降序排序结果。

示例按名称以字母逆序排序结果:

import mysql.connectormydb = mysql.connector.connect(host="localhost",user="yourusername",password="yourpassword",database="mydatabase"
)mycursor = mydb.cursor()sql = "SELECT * FROM customers ORDER BY name DESC"mycursor.execute(sql)myresult = mycursor.fetchall()for x in myresult:print(x)

删除记录

您可以使用"DELETE FROM"语句从现有表格中删除记录:

示例删除地址为"Mountain 21"的记录:

import mysql.connectormydb = mysql.connector.connect(host="localhost",user="yourusername",password="yourpassword",database="mydatabase"
)mycursor = mydb.cursor()sql = "DELETE FROM customers WHERE address = 'Mountain 21'"mycursor.execute(sql)mydbmit()print(mycursor.rowcount, "条记录已删除")

重要提示:请注意语句 mydbmit()。这是必需的,以使更改生效,否则不会对表格进行更改。

请注意DELETE语法中的WHERE子句:WHERE子句指定应删除哪些记录。如果省略WHERE子句,将删除所有记录!

防止SQL注入

通常认为,转义任何查询的值都是一种良好的做法,甚至在删除语句中也是如此。

这是为了防止SQL注入,这是一种常见的网络黑客技术,可以破坏或滥用您的数据库。

mysql.connector 模块使用占位符 %s 在删除语句中转义值:

示例使用占位符 %s 方法转义值:

import mysql.connectormydb = mysql.connector.connect(host="localhost",user="yourusername",password="yourpassword",database="mydatabase"
)mycursor = mydb.cursor()sql = "DELETE FROM customers WHERE address = %s"
adr = ("Yellow Garden 2", )mycursor.execute(sql, adr)mydbmit()print(mycursor.rowcount, "条记录已删除")

最后

为了方便其他设备和平台的小伙伴观看往期文章:公众号搜索Let us Coding,或者扫描下方二维码,关注公众号,即可获取最新文章。

看完如果觉得有帮助,欢迎点赞、收藏关注

更多推荐

MySQL 数据库查询与数据操作:使用 ORDER BY 排序和 DELETE 删除记录

本文发布于:2023-11-15 07:48:37,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1596190.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数据库查询   操作   数据   MySQL   ORDER

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!