连接mysql.py 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108
  1. # -*- coding: UTF-8 -*-
  2. ##============ ============###
  3. import pymysql
  4. conn = pymysql.connect(
  5. host='a.xdc.ink',
  6. port=3306,
  7. user='xdc',
  8. passwd='Xdc123@a',
  9. db='cmd',
  10. charset='utf8mb4'
  11. )
  12. # cursor = conn.cursor()
  13. # cursor.execute('show databases;')
  14. # alld = cursor.fetchall()
  15. # print(alld)
  16. # cursor.close()
  17. # conn.close()
  18. # 获取游标对象
  19. cursor = conn.cursor()
  20. ###============ 创建数据库 ============###
  21. # 定义sql语句
  22. # create_tabel_sql = """create table t1
  23. # (id int auto_increment primary key,
  24. # name varchar(10) not null,
  25. # age int not null
  26. # )"""
  27. # row = cursor.execute(create_tabel_sql)
  28. # print(row)
  29. # conn.commit() # 修改数据库内容要提交
  30. # cursor.close()
  31. # conn.close()
  32. ##============ 插入单条数据 ============###
  33. # insert_data_sql = "insert into t1(name, age) value(%s, %s);" # pymsql 的字符串格式化
  34. # row = cursor.execute(insert_data_sql,('xdc', 18)) # 传入数据,使用 ,
  35. # print(row)
  36. # conn.commit()
  37. # cursor.close()
  38. # conn.close()
  39. ##============ 插入多条数据 ============###
  40. insert_data_sql = "insert into t1(name, age) value(%s, %s);" # pymsql 的字符串格式化
  41. row = cursor.executemany(insert_data_sql,[('xdc', 18),('xdc1',19)]) # 传入数据,使用 ,
  42. print(row)
  43. conn.commit()
  44. cursor.close()
  45. conn.close()
  46. ##============ 查询数据 ============###
  47. # # 查询表
  48. # select_sql = "show tables;"
  49. # cursor.execute(select_sql)
  50. # # 打印出查询到的结果
  51. # print(cursor.fetchall())
  52. # cursor.close()
  53. # conn.close()
  54. class GetData(object):
  55. def __init__(self):
  56. self.conn = ''
  57. self.host = '127.0.0.1'
  58. self.port = 3306
  59. self.user = 'root'
  60. self.passwd = '123456'
  61. self.db = 'test'
  62. self.cnum = 5 #set retry number
  63. def init_connect(self):
  64. self.conn = pymysql.connect(host=self.host, user=self.user, passwd=self.passwd, db=self.db, port=self.port,
  65. charset='utf8')
  66. def get_data(self):
  67. self.init_connect()
  68. cur = self.conn.cursor()
  69. sql = "select * from testtable"
  70. cur.execute(sql)
  71. rs = cur.fetchall()
  72. cur.close()
  73. self.conn.close()
  74. return rs
  75. def run(self):
  76. count = 1
  77. while (count <= self.cnum):
  78. rs = self.get_data()
  79. if len(rs) > 0:
  80. print len(rs)
  81. break
  82. print count
  83. sleep(10)
  84. count += 1
  85. if __name__ == '__main__':
  86. gd = GetData()
  87. gd.run()