python操作mysql函式

2021-09-29 19:26:39 字數 1643 閱讀 9140

import pymysql

# host = "localhost"

# username = "root"

# psw = "123456"

# database = "test"

def cmdsql(sql):

"""更新資料庫操作"""

# 開啟資料庫連線

db = pymysql.connect(host, username, psw, database, charset='utf8')

# 使用cursor()方法獲取操作游標

cursor = db.cursor()

# 使用execute方法執行sql語句

try:

cursor.execute(sql)

db.commit()

except:

db.rollback()

print("出現錯誤!" + sql)

# 關閉資料庫連線

cursor.close()

db.close()

def querysql(sql):

"""查詢資料庫操作"""

# 開啟資料庫連線

db = pymysql.connect(host, username, psw, database, charset='utf8')

# 使用cursor()方法獲取操作游標

cursor = db.cursor()

# 使用execute方法執行sql語句

try:

cursor.execute(sql)

# 獲取所有記錄列表

results = cursor.fetchall()

except:

print("出現錯誤!" + sql)

# 關閉資料庫連線

cursor.close()

db.close()

return results

def sqlfetchone(sql):

"""查詢單行資料庫操作"""

# 開啟資料庫連線

db = pymysql.connect(host, username, psw, database, charset='utf8')

# 使用cursor()方法獲取操作游標

cursor = db.cursor()

cursor.execute(sql)

results = cursor.fetchone()

cursor.close()

db.close()

return results

def sqlfetchall(sql):

"""查詢全部行資料庫操作"""

# 開啟資料庫連線

db = pymysql.connect(host, username, psw, database, charset='utf8')

# 使用cursor()方法獲取操作游標

cursor = db.cursor()

cursor.execute(sql)

results = cursor.fetchall()

cursor.close()

db.close()

return results

網觀天下 

mysql 函式操作 mysql 數學操作函式

絕對值,圓周率 select abs 1 3 pi 平方根,求餘 select sqrt 9 mod 9,5 獲取整數的函式 select ceil 12.145 ceiling 12.145 floor 12.545 獲取隨機數 select rand 10,rand 1 mysql取得某一範圍隨...

python 函式操作

函式定義 用於 的重用 def print verse 函式體 print 鋤禾日當午 print verse print verse print verse def print verse verse name 函式體 if verse name 靜夜思 print 床前明月光 elif vers...

python函式操作邏輯 python 函式操作

匿名函式 匿名函式就是指不需要顯示的指定函式用lambda表示,預設return結果 在python中如果乙個元素被建立了,但是並沒有乙個變數來接受這個元素,則直譯器會自動釋放這個函式的記憶體空間 比起def而言,雖然lambda不能進行複雜的邏輯計算,但是他比def更加的簡便,但是需要配合別的函式...