mysql_connect.py 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. import mysql.connector
  2. from mysql.connector import Error
  3. MYSQL_CONFIG = {
  4. 'host': 'rm-bp1k5853td1r25g3n690.mysql.rds.aliyuncs.com',
  5. 'database': 'incentive',
  6. 'port': 3306,
  7. 'user': 'wx2016_longvideo',
  8. 'password': 'wx2016_longvideoP@assword1234',
  9. }
  10. def insert_content(gpt_res):
  11. """ 连接MySQL数据库并插入一行数据 """
  12. try:
  13. # 连接MySQL数据库
  14. conn = mysql.connector.connect(
  15. host=MYSQL_CONFIG['host'],
  16. database=MYSQL_CONFIG['database'],
  17. user=MYSQL_CONFIG['user'],
  18. password=MYSQL_CONFIG['password'],
  19. )
  20. if conn.is_connected():
  21. print('成功连接到数据库')
  22. cursor = conn.cursor()
  23. # 插入数据的SQL语句
  24. insert_query = """
  25. INSERT INTO video_content(video_id,key_words,search_keys,extra_keys,tone,target_audience,target_age,target_gender,address,theme)
  26. VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s)
  27. """
  28. # 准备要插入的数据,转换字典列表为元组列表
  29. data_to_insert = [(gpt_res['video_id'], gpt_res['key_words'], gpt_res['search_keys'], gpt_res['extra_keys'],
  30. gpt_res['tone'], gpt_res['target_audience'], gpt_res['target_age'], gpt_res['target_gender'],
  31. gpt_res['address'], gpt_res['theme'])]
  32. # 执行批量插入操作
  33. cursor.executemany(insert_query, data_to_insert)
  34. print('数据插入成功')
  35. # 检查插入结果
  36. # cursor.execute('SELECT * FROM employees')
  37. # records = cursor.fetchall()
  38. # print('插入的数据:', records)
  39. except Error as e:
  40. print('数据库连接或操作出错:', e)
  41. finally:
  42. if conn.is_connected():
  43. cursor.close()
  44. conn.close()
  45. print('数据库连接已关闭')
  46. # 执行函数
  47. # connect_insert()