sql.py 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. '''
  2. @author chenjunkai
  3. @time 20180612
  4. '''
  5. """
  6. 一般 Python 用于连接 MySQL 的工具:pymysql
  7. """
  8. import pymysql.cursors
  9. connection = pymysql.connect(host='localhost',
  10. user='root',
  11. password='1234',
  12. db='test',
  13. charset='utf8mb4',
  14. cursorclass=pymysql.cursors.DictCursor)
  15. # 保存评论
  16. def insert_comments(music_id, comments, detail, connection0):
  17. with connection0.cursor() as cursor:
  18. sql = "INSERT INTO `comments` (`MUSIC_ID`, `COMMENTS`, `DETAILS`) VALUES (%s, %s, %s)"
  19. cursor.execute(sql, (music_id, comments, detail))
  20. connection0.commit()
  21. # 保存音乐
  22. def insert_music(music_id, music_name, album_id):
  23. with connection.cursor() as cursor:
  24. sql = "INSERT INTO `musics` (`MUSIC_ID`, `MUSIC_NAME`, `ALBUM_ID`) VALUES (%s, %s, %s)"
  25. cursor.execute(sql, (music_id, music_name, album_id))
  26. connection.commit()
  27. # 保存专辑
  28. def insert_album(album_id, artist_id):
  29. with connection.cursor() as cursor:
  30. sql = "INSERT INTO `albums` (`ALBUM_ID`, `ARTIST_ID`) VALUES (%s, %s)"
  31. cursor.execute(sql, (album_id, artist_id))
  32. connection.commit()
  33. # 保存歌手
  34. def insert_artist(artist_id, artist_name):
  35. with connection.cursor() as cursor:
  36. sql = "INSERT INTO `artists` (`ARTIST_ID`, `ARTIST_NAME`) VALUES (%s, %s)"
  37. cursor.execute(sql, (artist_id, artist_name))
  38. connection.commit()
  39. # 获取所有歌手的 ID
  40. def get_all_artist():
  41. with connection.cursor() as cursor:
  42. sql = "SELECT `ARTIST_ID` FROM `artists` ORDER BY ARTIST_ID"
  43. cursor.execute(sql, ())
  44. return cursor.fetchall()
  45. # 获取所有专辑的 ID
  46. def get_all_album():
  47. with connection.cursor() as cursor:
  48. sql = "SELECT `ALBUM_ID` FROM `albums` ORDER BY ALBUM_ID"
  49. cursor.execute(sql, ())
  50. return cursor.fetchall()
  51. # 获取所有音乐的 ID
  52. def get_all_music():
  53. with connection.cursor() as cursor:
  54. sql = "SELECT `MUSIC_ID` FROM `musics` ORDER BY MUSIC_ID"
  55. cursor.execute(sql, ())
  56. return cursor.fetchall()
  57. # 获取前一半音乐的 ID
  58. def get_before_music():
  59. with connection.cursor() as cursor:
  60. sql = "SELECT `MUSIC_ID` FROM `musics` ORDER BY MUSIC_ID LIMIT 0, 800000"
  61. cursor.execute(sql, ())
  62. return cursor.fetchall()
  63. # 获取后一半音乐的 ID
  64. def get_after_music():
  65. with connection.cursor() as cursor:
  66. sql = "SELECT `MUSIC_ID` FROM `musics` ORDER BY MUSIC_ID LIMIT 800000, 1197429"
  67. cursor.execute(sql, ())
  68. return cursor.fetchall()
  69. def dis_connect():
  70. connection.close()