python从数据库中获得数据到numpy

ゝ一纸荒年。 2022-07-13 20:43 300阅读 0赞

使用mysql.connector连接mysql数据库

  1. import
  2. mysql.connector
  3. from
  4. itertools
  5. import
  6. chain
  7. import
  8. sys, os
  9. import
  10. numpy as np user
  11. =
  12. '
  13. root
  14. '
  15. pwd
  16. =
  17. '
  18. root
  19. '
  20. host
  21. =
  22. '
  23. 127.0.0.1
  24. '
  25. db
  26. =
  27. '
  28. lending
  29. '
  30. select_sql
  31. =
  32. "
  33. SELECT id,age FROM mytable
  34. "
  35. count_sql
  36. =
  37. "
  38. SELECT count(*) FROM mytable
  39. "
  40. cnx
  41. =
  42. mysql.connector.connect(user
  43. =
  44. user, password
  45. =
  46. pwd, host
  47. =
  48. host, database
  49. =
  50. db) cursor
  51. =
  52. cnx.cursor()
  53. try
  54. : cursor.execute(count_sql) count
  55. =
  56. 0
  57. #
  58. 显示总数
  59. for
  60. row1
  61. in
  62. cursor: count
  63. =
  64. row1[0];
  65. print
  66. (row1) test
  67. =
  68. np.arange(count
  69. *
  70. 2
  71. ).reshape(count,
  72. 2
  73. ) numrows
  74. =
  75. cursor.execute(select_sql)
  76. print
  77. (
  78. "
  79. ================================
  80. "
  81. ) index
  82. =
  83. 0;
  84. for
  85. row
  86. in
  87. cursor:
  88. print
  89. (row) test[index,:]
  90. =
  91. np.fromiter(row, dtype
  92. =
  93. (int,int), count
  94. =
  95. 1
  96. ) index
  97. =
  98. index
  99. +
  100. 1
  101. print
  102. (test)
  103. except
  104. mysql.connector.Error as err:
  105. print
  106. (
  107. "
  108. query table 'mytable' failed.
  109. "
  110. )
  111. print
  112. (
  113. "
  114. Error: {}
  115. "
  116. .format(err.msg)) sys.exit() cnx.commit() cursor.close() cnx.close()

Numpy常见数据类型

image

发表评论

表情:
评论列表 (有 0 条评论,300人围观)

还没有评论,来说两句吧...

相关阅读