Python MySQL 数据库查询:选择数据、使用筛选条件、防止 SQL 注入

编程入门 行业动态 更新时间:2024-10-24 02:29:40

Python MySQL <a href=https://www.elefans.com/category/jswz/34/1771047.html style=数据库查询:选择数据、使用筛选条件、防止 SQL 注入"/>

Python MySQL 数据库查询:选择数据、使用筛选条件、防止 SQL 注入

从表格中选择数据

要从MySQL中的表格中选择数据,请使用"SELECT"语句:

示例选择"customers"表格中的所有记录,并显示结果:

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

注意:我们使用 fetchall() 方法,该方法从上次执行的语句中获取所有行。

选择列

要仅选择表格中的某些列,请使用"SELECT"语句,后跟列名:

示例仅选择name和address列:

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

使用 fetchone() 方法

如果您只对一行数据感兴趣,可以使用 fetchone() 方法。

fetchone() 方法将返回结果的第一行:

示例仅获取一行:

import mysql.connectormydb = mysql.connector.connect(host="localhost",user="yourusername",password="yourpassword",database="mydatabase"
)mycursor = mydb.cursor()mycursor.execute("SELECT * FROM customers")myresult = mycursor.fetchone()print(myresult)

这是您提供的内容的Markdown排版,按照您的要求进行了整理。如果需要进一步的编辑或修改,请告诉我。

使用筛选条件选择记录

在从表格中选择记录时,您可以使用"WHERE"语句来筛选选择的记录:

示例选择地址为"Park Lane 38"的记录:

import mysql.connectormydb = mysql.connector.connect(host="localhost",user="yourusername",password="yourpassword",database="mydatabase"
)mycursor = mydb.cursor()sql = "SELECT * FROM customers WHERE address ='Park Lane 38'"mycursor.execute(sql)myresult = mycursor.fetchall()for x in myresult:print(x)

通配符字符

您还可以选择以给定字母或短语开头、包含或以给定字母或短语结尾的记录。

使用 % 来表示通配符字符:

示例选择地址中包含单词 “way” 的记录:

import mysql.connectormydb = mysql.connector.connect(host="localhost",user="yourusername",password="yourpassword",database="mydatabase"
)mycursor = mydb.cursor()sql = "SELECT * FROM customers WHERE address LIKE '%way%'"mycursor.execute(sql)myresult = mycursor.fetchall()for x in myresult:print(x)

防止SQL注入

当查询值由用户提供时,应该转义这些值。

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

mysql.connector 模块具有转义查询值的方法:

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

import mysql.connectormydb = mysql.connector.connect(host="localhost",user="yourusername",password="yourpassword",database="mydatabase"
)mycursor = mydb.cursor()sql = "SELECT * FROM customers WHERE address = %s"
adr = ("Yellow Garden 2", )mycursor.execute(sql, adr)myresult = mycursor.fetchall()for x in myresult:print(x)

最后

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

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

更多推荐

Python MySQL 数据库查询:选择数据、使用筛选条件、防止 SQL 注入

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

发布评论

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

>www.elefans.com

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