1.項目中使用PyMySQL一些案例web
創建一個config.py 用於存儲配置文件sql
2.測試數據庫
##獲取數據 from config import ctf '''connection對象支持的方法 cursor() 使用該鏈接建立並返回遊標 commit() 提交當前事務 rollback() 回滾當前事務 close() 關閉鏈接 ''' '''cursor 對象支持的方法 execute(op) 執行一個數據庫的查詢命令 fetchone() 取得結果集的下一行 fetchmany(size) 得到結果記得下幾行 fetchall() 獲取結果集中的全部行 rowcount() 獲取數據條數或者影響條數 close() 關閉遊標 ''' def get_data(): try: with ctf.con_localhost.cursor() as cursor: # 建立一個新的sql語句 sql = "insert into web_sys_user(username, tel, password, oper) values ('%s','%s','%s','%s')" params = (1, 2, 3, 4) cursor.execute(sql, params) print('成功插入', cursor.rowcount, '條數據') ctf.con_localhost.commit() with ctf.con_localhost.cursor() as cursor: sql = "select * from web_sys_user" cursor.execute(sql) print('成功查詢', cursor.rowcount, '條數據') ctf.con_localhost.commit() finally: # 關閉鏈接 ctf.con_localhost.close() # 關閉遊標 ctf.con_localhost.cursor().close() if __name__ == '__main__': get_data()
3.結果集測試