Python MySQL – Where子句用法详细介绍

2021年3月14日14:33:20 发表评论 579 次浏览

Where子句在MySQL数据库中用于根据所需条件过滤数据。你可以使用where子句在MySQL数据库中获取, 删除或更新一组特定的数据。

语法

SELECT column1, column2, …。来自[表格名称]的cloumnN [条件];

上面的语法用于根据条件显示一组特定的数据。

例子:考虑下面一个名为College的数据库, 该表的名称为Student。

数据库的架构:

python-db-schema

数据库:

python-db-table

Python中的子句

在Python中使用where子句的步骤是:

  1. 首先在MySQL和Python程序之间建立连接。通过导入mysql.connector软件包并使用mysql.connector.connect()方法, 用于将用户名, 密码, 主机(可选的默认值:localhost)和数据库(可选的)作为参数传递给该方法。
  2. 现在, 使用以下命令在上面创建的连接对象上创建一个游标对象光标()方法。数据库游标是一种控制结构, 可以遍历数据库中的记录。
  3. 然后, 通过将其通过来执行where子句语句执行()方法。
import mysql.connector
   
#Establishing connection
conn = mysql.connector.connect(user = 'your_username' , host = 'localhost' , password = 'your_password' , database = 'College' )
   
# Creating a cursor object using 
# the cursor() method
mycursor = conn.cursor();
   
# SQL Query
sql = "select * from Student where Roll_no >= 3;"
   
# Executing query
mycursor.execute(sql)
   
myresult = mycursor.fetchall()
   
for x in myresult:
     print (x)
  
# Closing the connection
conn.close()

输出如下:

python-where-mysql

注意怪胎!巩固你的基础Python编程基础课程和学习基础知识。

首先, 你的面试准备可通过以下方式增强你的数据结构概念:Python DS课程。


木子山

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: