Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # -*- coding: utf-8 -*-
- """ Exemplo (CRUD) de utilização do PyMySQL.
- ======================
- Instalação do conector
- ======================
- .. code-block:: bash
- pip install PyMySQL
- ===================
- Confirgurar o MySQL
- ===================
- Se o banco estiver em outras máquinas lembre-se de configurar o
- ``bind-adress`` no arquivo ``/etc/mysql/mysql.conf.d``.
- .. code-block::
- bind-address = 0.0.0.0
- Ou configure conforme a sua necessidade.
- **OBS:** Após realizar qualquer tipo de configuração no MySQL reinicie o serviço:
- .. code-block:: bash
- sudo systemctl restart mysql.service
- O usuário do MySQL tem que ter acesso ao banco:
- .. code-block:: mysql
- CREATE USER 'NomeDoUsuario'@'localhost' IDENTIFIED BY 'SenhaDoUsuario';
- GRANT ALL PRIVILEGES ON *.* TO 'NomeDoUsuario'@'localhost' WITH GRANT OPTION;
- .. code-block:: mysql
- CREATE USER 'NomeDoUsuario'@'%' IDENTIFIED BY 'SenhaDoUsuario';
- GRANT ALL PRIVILEGES ON *.* TO 'username'@'%' WITH GRANT OPTION;
- Se a permissão não for ativa automaticamente utilize:
- .. code-block:: mysql
- FLUSH PRIVILEGES;
- """
- import pymysql.cursors
- class ConectarDB():
- def __init__(self):
- try:
- self.conexao = pymysql.connect(host='192.168.0.101',
- user='python',
- password='123456',
- db='testepy',
- charset='utf8mb4',
- cursorclass=pymysql.cursors.DictCursor)
- except Exception as e:
- print('[!] Falha ao conectar no servidor [!]: ', e)
- def criar_tabela(self):
- try:
- with self.conexao.cursor() as cursor:
- cursor.execute("""CREATE TABLE IF NOT EXISTS `usuario` (
- `id` int(11) NOT NULL AUTO_INCREMENT,
- `nome` VARCHAR(45) NOT NULL,
- `senha` VARCHAR(45) NOT NULL,
- `email` VARCHAR(45) NOT NULL,
- PRIMARY KEY (`id`)
- )ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin
- AUTO_INCREMENT=1""")
- except Exception as e:
- print('[!] Falha ao criar a tabela [!]: ', e)
- def criar_usuario(self):
- try:
- with self.conexao.cursor() as cursor:
- cursor.execute("""INSERT INTO `usuario` (
- `nome`, `senha`, email ) VALUES(
- 'Renato', '123456', 'renato@teste.com')""")
- self.conexao.commit()
- print('Usuário criado com sucesso')
- except Exception as e:
- print('[!] Falha ao criar novo usuário [!]: ', e)
- def consultar_todos(self):
- try:
- with self.conexao.cursor() as cursor:
- cursor.execute("""SELECT `*` FROM `usuario`""")
- dados = cursor.fetchall()
- print(dados)
- except Exception as e:
- print('[!] Não foi possível realizar a consulta [!]: ', e)
- def consultar_usuario(self):
- try:
- with self.conexao.cursor() as cursor:
- cursor.execute("""SELECT `id`, `nome` FROM `usuario`
- WHERE `email`=%s""", ('renato@teste.com'))
- dados = cursor.fetchone()
- print(dados)
- except Exception as e:
- print('[!] Não foi possível realizar a consulta [!]: ', e)
- def deletar_usuario(self):
- try:
- with self.conexao.cursor() as cursor:
- cursor.execute("""DELETE FROM `usuario` WHERE `id`=%s""", (2))
- self.conexao.commit()
- print('Usuário REMOVIDO com sucesso')
- except Exception as e:
- print('[!] Falha ao remover registro [!]: ', e)
- if __name__ == '__main__':
- conectar = ConectarDB()
- # conectar.criar_tabela()
- # conectar.criar_usuario()
- # conectar.consultar_todos()
- # conectar.consultar_usuario()
- # conectar.deletar_usuario()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement