欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

MySQL 使用 ORDER BY 排序和 DELETE 刪除記錄的操作過程

 更新時間:2023年11月13日 09:22:09   作者:小萬哥  
這篇文章主要介紹了MySQL 使用 ORDER BY 排序和 DELETE 刪除記錄的操作過程,即數(shù)據(jù)庫查詢與數(shù)據(jù)操作,本文通過示例代碼給大家介紹的非常詳細,需要的朋友參考下吧

使用 ORDER BY 進行排序

使用 ORDER BY 語句按升序或降序?qū)Y(jié)果進行排序。

ORDER BY 關(guān)鍵字默認按升序排序。要按降序排序結(jié)果,使用 DESC 關(guān)鍵字。

示例按名稱按字母順序排序結(jié)果:

import mysql.connector
mydb = 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 關(guān)鍵字以降序排序結(jié)果。

示例按名稱以字母逆序排序結(jié)果:

import mysql.connector
mydb = 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"語句從現(xiàn)有表格中刪除記錄:

示例刪除地址為"Mountain 21"的記錄:

import mysql.connector
mydb = 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)
mydb.commit()
print(mycursor.rowcount, "條記錄已刪除")

重要提示:請注意語句 mydb.commit()。這是必需的,以使更改生效,否則不會對表格進行更改。

請注意DELETE語法中的WHERE子句:WHERE子句指定應刪除哪些記錄。如果省略WHERE子句,將刪除所有記錄!

防止SQL注入

通常認為,轉(zhuǎn)義任何查詢的值都是一種良好的做法,甚至在刪除語句中也是如此。

這是為了防止SQL注入,這是一種常見的網(wǎng)絡(luò)黑客技術(shù),可以破壞或濫用您的數(shù)據(jù)庫。

mysql.connector 模塊使用占位符 %s 在刪除語句中轉(zhuǎn)義值:

示例使用占位符 %s 方法轉(zhuǎn)義值:

import mysql.connector
mydb = 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)
mydb.commit()
print(mycursor.rowcount, "條記錄已刪除")

到此這篇關(guān)于MySQL 數(shù)據(jù)庫查詢與數(shù)據(jù)操作:使用 ORDER BY 排序和 DELETE 刪除記錄的文章就介紹到這了,更多相關(guān)mysql ORDER BY 排序和 DELETE 刪除記錄內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評論