Advertisement
Guest User

Untitled

a guest
May 29th, 2017
549
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 3.92 KB | None | 0 0
  1. # -*- coding: utf-8 -*-
  2.  
  3. """ Exemplo (CRUD) de utilização do PyMySQL.
  4. ======================
  5. Instalação do conector
  6. ======================
  7.  
  8. .. code-block:: bash
  9.  
  10. pip install PyMySQL
  11.  
  12. ===================
  13. Confirgurar o MySQL
  14. ===================
  15.  
  16. Se o banco estiver em outras máquinas lembre-se de configurar o
  17. ``bind-adress`` no arquivo ``/etc/mysql/mysql.conf.d``.
  18.  
  19. .. code-block::
  20.  
  21. bind-address = 0.0.0.0
  22.  
  23. Ou configure conforme a sua necessidade.
  24.  
  25. **OBS:** Após realizar qualquer tipo de configuração no MySQL reinicie o serviço:
  26.  
  27. .. code-block:: bash
  28.  
  29. sudo systemctl restart mysql.service
  30.  
  31. O usuário do MySQL tem que ter acesso ao banco:
  32.  
  33. .. code-block:: mysql
  34.  
  35. CREATE USER 'NomeDoUsuario'@'localhost' IDENTIFIED BY 'SenhaDoUsuario';
  36.  
  37. GRANT ALL PRIVILEGES ON *.* TO 'NomeDoUsuario'@'localhost' WITH GRANT OPTION;
  38.  
  39.  
  40. .. code-block:: mysql
  41.  
  42. CREATE USER 'NomeDoUsuario'@'%' IDENTIFIED BY 'SenhaDoUsuario';
  43.  
  44. GRANT ALL PRIVILEGES ON *.* TO 'username'@'%' WITH GRANT OPTION;
  45.  
  46. Se a permissão não for ativa automaticamente utilize:
  47.  
  48. .. code-block:: mysql
  49.  
  50. FLUSH PRIVILEGES;
  51. """
  52.  
  53. import pymysql.cursors
  54.  
  55.  
  56. class ConectarDB():
  57. def __init__(self):
  58. try:
  59. self.conexao = pymysql.connect(host='192.168.0.101',
  60. user='python',
  61. password='123456',
  62. db='testepy',
  63. charset='utf8mb4',
  64. cursorclass=pymysql.cursors.DictCursor)
  65. except Exception as e:
  66. print('[!] Falha ao conectar no servidor [!]: ', e)
  67.  
  68. def criar_tabela(self):
  69. try:
  70. with self.conexao.cursor() as cursor:
  71. cursor.execute("""CREATE TABLE IF NOT EXISTS `usuario` (
  72. `id` int(11) NOT NULL AUTO_INCREMENT,
  73. `nome` VARCHAR(45) NOT NULL,
  74. `senha` VARCHAR(45) NOT NULL,
  75. `email` VARCHAR(45) NOT NULL,
  76. PRIMARY KEY (`id`)
  77. )ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin
  78. AUTO_INCREMENT=1""")
  79. except Exception as e:
  80. print('[!] Falha ao criar a tabela [!]: ', e)
  81.  
  82. def criar_usuario(self):
  83. try:
  84. with self.conexao.cursor() as cursor:
  85. cursor.execute("""INSERT INTO `usuario` (
  86. `nome`, `senha`, email ) VALUES(
  87. 'Renato', '123456', 'renato@teste.com')""")
  88. self.conexao.commit()
  89. print('Usuário criado com sucesso')
  90. except Exception as e:
  91. print('[!] Falha ao criar novo usuário [!]: ', e)
  92.  
  93. def consultar_todos(self):
  94. try:
  95. with self.conexao.cursor() as cursor:
  96. cursor.execute("""SELECT `*` FROM `usuario`""")
  97. dados = cursor.fetchall()
  98. print(dados)
  99. except Exception as e:
  100. print('[!] Não foi possível realizar a consulta [!]: ', e)
  101.  
  102. def consultar_usuario(self):
  103. try:
  104. with self.conexao.cursor() as cursor:
  105. cursor.execute("""SELECT `id`, `nome` FROM `usuario`
  106. WHERE `email`=%s""", ('renato@teste.com'))
  107. dados = cursor.fetchone()
  108. print(dados)
  109. except Exception as e:
  110. print('[!] Não foi possível realizar a consulta [!]: ', e)
  111.  
  112. def deletar_usuario(self):
  113. try:
  114. with self.conexao.cursor() as cursor:
  115. cursor.execute("""DELETE FROM `usuario` WHERE `id`=%s""", (2))
  116. self.conexao.commit()
  117. print('Usuário REMOVIDO com sucesso')
  118. except Exception as e:
  119. print('[!] Falha ao remover registro [!]: ', e)
  120.  
  121.  
  122. if __name__ == '__main__':
  123. conectar = ConectarDB()
  124. # conectar.criar_tabela()
  125. # conectar.criar_usuario()
  126. # conectar.consultar_todos()
  127. # conectar.consultar_usuario()
  128. # conectar.deletar_usuario()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement