python3結合pymysql模塊對數據庫進行建表,增, 改,查

# !/usr/bin/python3 # -*- coding: utf-8 -*- import pymysql OPTION = { "check_sql_data": "0", "create_tables": "1", "add_sql_data": "2", "put_sql_data": "3", } def __get_connect(): # 連接數據庫 connect = pymysql.Connect( host=host, port=port, user=user, passwd='password', db="db_name", charset='utf8' ) return connect def create_tables(): tables = "5" # 創建數據庫表 create_table = """ create table my{}( id int unsigned primary key auto_increment, first_name char(10) not null, last_name char(10) not null, age int unsigned, sex tinyint, money float ) """.format(tables) try: connect = __get_connect() cursor = connect.cursor() cursor.execute(create_table) except Exception as e: connect.rollback() # 事務回滾 print('事務處理失敗', e) else: connect.commit() # 事務提交 print('事務處理成功', cursor.rowcount) # 關閉連接 cursor.close() connect.close() def check_sql_data(): # 數據庫查詢 check_sql = "select * from my23" try: connect = __get_connect() cursor = connect.cursor() cursor.execute(check_sql) data = cursor.fetchmany(11) except Exception as e: connect.rollback() # 事務回滾 print('數據查詢失敗', e) return "數據查詢失敗" else: connect.commit() # 事務提交 print("查詢到{}條數據," .format(cursor.rowcount), data) # 關閉連接 cursor.close() connect.close() def add_sql_data(): # 往數據庫表增加數據 add_sql = "insert into myt033(first_name,last_name,age,sex,money) values(%s,%s,%s,%s,%s)" try: connect = __get_connect() cursor = connect.cursor() cursor.executemany(add_sql, [("Liu", "Mick", 90, 1, 9.9), ("L", "M", 12, 3, 44)]) except Exception as e: connect.rollback() # 事務回滾 print('數據新增失敗', e) else: connect.commit() # 事務提交 print("新增{}數據成功".format(cursor.rowcount)) # 關閉連接 cursor.close() connect.close() def put_sql_data(): # 修改數據庫數據 put_sql = "update my23 set first_name = %s where id = %s" try: connect = __get_connect() cursor = connect.cursor() cursor.executemany(put_sql, [("test11", 1), ("test211", 2)]) print("修改{}條數據成功".format(cursor.rowcount)) except Exception as e: connect.rollback() # 事務回滾 print('數據修改失敗', e) else: connect.commit() # 事務提交 print("{}條數據成功".format(cursor.rowcount)) # 關閉連接 cursor.close() connect.close() def option_in(arg1): if arg1 == OPTION.get("check_sql_data"): check_sql_data() elif arg1 == OPTION.get("create_tables"): create_tables() elif arg1 == OPTION.get("add_sql_data"): add_sql_data() elif arg1 == OPTION.get("put_sql_data"): put_sql_data() else: print("您輸入的參數無效,請輸入數字, 只支持0~3") if __name__ == "__main__": arg = input("請輸入:") option_in(arg) # python3交流羣: 305357273
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章