您好,登錄后才能下訂單哦!
安裝pymysql
參考:https://github.com/PyMySQL/PyMySQL/
pip install pymsql
實例一
import pymysql # 創建連接 # 參數依次對應服務器地址,用戶名,密碼,數據庫 conn = pymysql.connect(host='127.0.0.1', user='root', passwd='123456', db='demo') # 創建游標 cursor = conn.cursor(cursor=pymysql.cursors.DictCursor) # 執行語句返回影響的行數 effect_row = cursor.execute("select * from course") print(effect_row) # 獲取所有數據 result = cursor.fetchall() result = cursor.fetchone() # 獲取下一個數據 result = cursor.fetchone() # 獲取下一個數據(在上一個的基礎之上) # cursor.scroll(-1, mode='relative') # 相對位置移動 # cursor.scroll(0,mode='absolute') # 絕對位置移動 # 提交,不然無法保存新建或者修改的數據 conn.commit() # 關閉游標 cursor.close() # 關閉連接 conn.close()
實例二
import pymysql # 建立連接 conn = pymysql.connect(host='127.0.0.1', user='root', passwd='123456', db='demo') # 創建游標 cursor = conn.cursor(cursor=pymysql.cursors.DictCursor) # 插入一條數據 %s是占位符 占位符之間用逗號隔開 effect_row = cursor.execute("insert into course(cou_name,time) values(%s,%s)", ("Engilsh", 100)) print(effect_row) conn.commit() cursor.close() conn.close()
實例三
import pymysql.cursors # Connect to the database connection = pymysql.connect(host='localhost', user='user', password='passwd', db='db', charset='utf8mb4', cursorclass=pymysql.cursors.DictCursor) try: with connection.cursor() as cursor: # Create a new record sql = "INSERT INTO `users` (`email`, `password`) VALUES (%s, %s)" cursor.execute(sql, ('webmaster@python.org', 'very-secret')) # connection is not autocommit by default. So you must commit to save # your changes. connection.commit() with connection.cursor() as cursor: # Read a single record sql = "SELECT `id`, `password` FROM `users` WHERE `email`=%s" cursor.execute(sql, ('webmaster@python.org',)) result = cursor.fetchone() print(result) finally: connection.close()
總結
以上就是這篇文章的全部內容了,希望本文的內容對大家的學習或者工作具有一定的參考學習價值,謝謝大家對億速云的支持。如果你想了解更多相關內容請查看下面相關鏈接
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。