一: 安裝pymysqlmysql
pip3 install pymysqlsql
二: 查詢操做數據庫
import pymysql # 打開數據庫鏈接 db = pymysql.connect(host='localhost', user='root', password='123456', db='userinfo', port=3306) # 使用cursor()方法獲取操做遊標 cur = db.cursor() #1, 查詢操做 # 編寫sql,查詢語句 s_info 對應的表名 sql = "select * from s_info" try: cur.execute(sql) # 執行sql語句 # results = cur.fetchall() # 獲取一行 # result_one = cur.fetchone() # print(result_one) # 獲取多個 result_many = cur.fetchmany(3) print(result_many) # print(results) # 返回全部的數據一元組套元組的形式 # print("id", "name", "pwd") # #遍歷結果 # for row in results: # id = row[0] # name = row[1] # password = row[2] # print(id, name, password) except Exception as e: raise e finally: db.close()
三: 插入操做ide
import pymysql #2 插入操做 db = pymysql.connect(host='localhost', user='root', password='123456', port=3306, db='userinfo') # 使用遊標 cur = db.cursor() sql_insert = "insert into s_info(name, pwd) values('egon', '456')" try: cur.execute(sql_insert) db.commit() except Exception as e: db.rollback() raise e finally: cur.close() db.close()
四: 修改操做fetch
import pymysql # 獲取數據庫 db = pymysql.connect(host='localhost', user='root', password='123456', db='userinfo', port=3306) # 獲取遊標 cur = db.cursor() # sql改語句 sql = "update s_info set name=%s where id=7" try: cur.execute(sql, "egon") db.commit() except Exception as e: raise e finally: cur.close() db.close()
五: 刪除操做spa
import pymysql db = pymysql.connect(host='localhost', user='root', password='123456', port=3306, db='userinfo') cur = db.cursor() sql = "delete from s_info where id=1" try: cur.execute(sql) db.commit() except Exception as e: raise e finally: cur.close() db.close()