PyMySQL模塊
-
安裝PyMySQL模塊
pip install pymysql
-
PyMySQL查詢數(shù)據(jù)
import pymysql # 連接數(shù)據(jù)庫 connection = pymysql.connect(host='127.0.0.1', user='root', password='123456', database='DB') # 獲取游標對象,cursor=pymysql.cursors.DictCursor 表示返回字典類型的數(shù)據(jù) cursor = connection.cursor(cursor=pymysql.cursors.DictCursor) # 需要執(zhí)行的sql語句,一般情況下Python只操作數(shù)據(jù)表中的數(shù)據(jù),查詢用戶信息表中的user和password sql = 'select * from user_info where user=%s and password=%s;' # 執(zhí)行MySQL命令,sql后面?zhèn)魅雞ser和password參數(shù),可以防止sql注入 cursor.execute(sql,(user,password)) # 獲取執(zhí)行MySQL命令的一個值 result = cursor.fetchone() # 獲取執(zhí)行MySQL命令的多個值 result = cursor.fetchmany(10) # 獲取執(zhí)行MySQL命令的所有值 result = cursor.fetchall() # 關(guān)閉游標對象 cursor.close() # 斷開數(shù)據(jù)庫連接 connection.close()
-
PyMySQL增、刪、改數(shù)據(jù)
import pymysql # 連接數(shù)據(jù)庫 connection = pymysql.connect(host='127.0.0.1', user='root', password='123456', database='DB') # 獲取游標對象 cursor = connection.cursor(cursor=pymysql.cursors.DictCursor) # 需要執(zhí)行的sql語句 sql = 'insert into tb(username,password) values ("python","123456");' try: # 執(zhí)行MySQL命令 cursor.execute(sql) # 提交到數(shù)據(jù)庫執(zhí)行,查詢不用寫這句,但增、刪、改需要 connection.commit() except Exception as e: # 如果出現(xiàn)異常,打印異常 print(e) # 如果出現(xiàn)異常則回滾try中的語句 connection.rollback() # 關(guān)閉游標對象 cursor.close() # 斷開數(shù)據(jù)庫連接 connection.close()