mysql_connector.py 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. # Python安装 MySQL Connector 驱动程序,访问 MySQL 数据库和查询修改 WordPress 博客文章
  2. # https://262235.xyz/index.php/archives/707/
  3. import mysql.connector
  4. mydb = mysql.connector.connect(
  5. host="localhost",
  6. user="root",
  7. passwd="yourpassword"
  8. )
  9. ## 使用 `SHOW DATABASES` 语句列出系统中的所有数据库
  10. c = mydb.cursor()
  11. c.execute("SHOW DATABASES")
  12. for x in c:
  13. print(x)
  14. ## WordPress 存放文章的数据表名 wp_posts,使用 SELECT 查询博客的文章
  15. c = mydb.cursor()
  16. c.execute("USE wordpress")
  17. c.execute("SELECT * FROM wp_posts LIMIT 5")
  18. result = c.fetchall()
  19. for x in result:
  20. print(x)
  21. ### 选取列-只选择表中的某些列,请使用 "SELECT" 语句,后跟列名
  22. c.execute("SELECT ID, post_title, guid, post_type FROM wp_posts LIMIT 5")
  23. result = c.fetchall()
  24. for x in result: print(x)
  25. ### 用 fetchall() 方法,该方法从最后执行的语句中获取所有行
  26. ### 如果只需一行或者逐行,可以使用 fetchone() 方法, 将返回结果的第一行
  27. c.execute("SELECT ID, post_title, guid, post_type FROM wp_posts LIMIT 5")
  28. result = c.fetchone()
  29. print(result)
  30. result = c.fetchone(); print(result)
  31. ### WordPress文章内容批量替换文字的方法 更新表: 使用 UPDATE 语句来更新表中的现有记录
  32. sql = "UPDATE wp_posts SET post_content = replace(post_content,'nginx','nginx-php')"
  33. c.execute(sql)
  34. mydb.commit()
  35. print(c.rowcount, "record(s) affected")