Advertisement
diegomrodrigues

Utilizando o PostgreSQL no Python

Mar 27th, 2018
168
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.11 KB | None | 0 0
  1. '''
  2. Utilizando o PostgreSQL no Python
  3.  
  4. Instalar o módulo psycopg2
  5. pip install psycopg2
  6.  
  7. Curso de Python 3
  8. https://www.udemy.com/curso-de-python3/
  9.  
  10. Diego Mendes Rodrigues
  11. '''
  12.  
  13. import psycopg2
  14.  
  15. conexao = psycopg2.connect(dbname='dbexemplo',
  16.                            user='demo',
  17.                            password='DeM@123@Po',
  18.                            host='127.0.0.1',
  19.                            port='5432')
  20.  
  21. cursor = conexao.cursor()
  22.  
  23. cursor.execute('DROP TABLE pessoas;');
  24.  
  25. cursor.execute('CREATE TABLE pessoas (codigo SERIAL PRIMARY KEY, nome TEXT, idade INTEGER);')
  26.  
  27. cursor.execute('INSERT INTO pessoas (nome, idade) VALUES (%s, %s)',('Bruna Mendes', 29))
  28. cursor.execute('INSERT INTO pessoas (nome, idade) VALUES (%s, %s)',('Julia Neau', 2))
  29. cursor.execute('INSERT INTO pessoas (nome, idade) VALUES (%s, %s)',('Regina Marcia', 55))
  30.  
  31. conexao.commit()
  32.  
  33. cursor.execute('SELECT * FROM pessoas;')
  34.  
  35. for linha in cursor.fetchall():
  36.     print('\nCódigo.: {} '.format(linha[0]))
  37.     print('Nome...: {} '.format(linha[1]))
  38.     print('Idade..: {} '.format(linha[2]))
  39.  
  40. cursor.close()
  41. conexao.close()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement