Python远程将数据写入Mysql

import pymysql def write_data_to_mysql(data, table_name): # 连接参数 host = 'localhost' port = 3306 user = 'your_username' password = 'your_password' database = 'your_database' # 创建连接 connection = pymysql.connect( host=host, port=port, user=user, password=password, db=database, charset='utf8mb4' ) try: cursor = connection.cursor() # 假设data是一个字典,包含要插入的数据 columns = ', '.join(data.keys()) values = ', '.join(f"'{v}'" for v in data.values()) insert_query = f"INSERT INTO {table_name} ({columns}) VALUES ({values})" # 执行写操作 cursor.execute(insert_query) # 提交事务 connection.commit() finally: cursor.close() connection.close() # 示例数据 example_data = { 'column1': 'value1', 'column2': 'value2', } # 调用函数写入数据 write_data_to_mysql(example_data,'your_table_name')
上一篇:OpenHarmony开发实例:【鸿蒙.bin文件烧录】