python 使用sql查詢資料庫返回空集判斷

2021-10-14 11:02:19 字數 650 閱讀 8728

python中連線資料庫後,發出查詢語句而後逐條處理,標準語句如下:

db = pymysql.connect("localhost", "使用者名稱", "口令", "資料庫", charset='utf8' )

cursor = db.cursor()

cursor.execute(sqlt)

results = cursor.fetchall()

for row in results:

逐條處理

db.close()

以上語句段預設返回有資料記錄,但如果一條select語句的返回集是空,可以對其中的results進行判斷,上述**可改為:

db = pymysql.connect("localhost", "使用者名稱", "口令", "資料庫", charset='utf8' )

cursor = db.cursor()

cursor.execute(sqlt)

results = cursor.fetchall()

if len(results) !=0:

for row in results:

逐條處理

db.close()

當然如果不進行判斷,實際上也不影響什麼。

sql鑲嵌查詢 SQL 查詢巢狀使用

示例表如下 create table it student id int primary key auto increment,主鍵id name varchar 20 姓名 gender enum male female 性別 class id tinyint unsigned,班級號 age i...

SQL 使用子查詢

sql還允許建立子查詢,巢狀再其他查詢中的查詢。下面舉幾個栗子來理解一下 現在結合1 2這兩個查詢,把第乙個查詢 返回訂單號的那乙個 變為子查詢 select cust id from orders where order num in select order num from orderitem...

SQL使用 聯合查詢

a表 b表 c表 內連線 inner join 內連線 僅顯示兩個表中匹配行,即兩表中都有才顯示。sql如下 select a.id as aid,a.content as acontent,b.id as bid,b.content as bcontent from a inner join b ...