做个网站多少钱一年,无极网络科技有限公司,凡客生活,网页设计规范2018从表格中选择数据
要从MySQL中的表格中选择数据#xff0c;请使用SELECT语句#xff1a;
示例选择customers表格中的所有记录#xff0c;并显示结果#xff1a;
import mysql.connectormydb mysql.connector.connect(hostlocalhost请使用SELECT语句
示例选择customers表格中的所有记录并显示结果
import mysql.connectormydb mysql.connector.connect(hostlocalhost,useryourusername,passwordyourpassword,databasemydatabase
)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(hostlocalhost,useryourusername,passwordyourpassword,databasemydatabase
)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(hostlocalhost,useryourusername,passwordyourpassword,databasemydatabase
)mycursor mydb.cursor()mycursor.execute(SELECT * FROM customers)myresult mycursor.fetchone()print(myresult)这是您提供的内容的Markdown排版按照您的要求进行了整理。如果需要进一步的编辑或修改请告诉我。
使用筛选条件选择记录
在从表格中选择记录时您可以使用WHERE语句来筛选选择的记录
示例选择地址为Park Lane 38的记录
import mysql.connectormydb mysql.connector.connect(hostlocalhost,useryourusername,passwordyourpassword,databasemydatabase
)mycursor mydb.cursor()sql SELECT * FROM customers WHERE address Park Lane 38mycursor.execute(sql)myresult mycursor.fetchall()for x in myresult:print(x)通配符字符
您还可以选择以给定字母或短语开头、包含或以给定字母或短语结尾的记录。
使用 % 来表示通配符字符
示例选择地址中包含单词 “way” 的记录
import mysql.connectormydb mysql.connector.connect(hostlocalhost,useryourusername,passwordyourpassword,databasemydatabase
)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(hostlocalhost,useryourusername,passwordyourpassword,databasemydatabase
)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关注后即可获取最新文章推送
看完如果觉得有帮助欢迎 点赞、收藏、关注