■ connect 함수를 사용해 데이터베이스에 연결하는 방법을 보여준다.
▶ 예제 코드 1 (PY)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
import psycopg2 with psycopg2.connect(host = "192.168.29.118", port = "5432", database = "testdb", user = "testuser1", password = "test1234") as connection: with connection.cursor() as cursor: cursor.execute("SELECT * FROM test;") resultList = cursor.fetchall() for result in resultList: print(result) """ (1, '홍길동', 20) (2, '김철수', 30) (3, '이영희', 25) """ |
▶ 예제 코드 2 (PY)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
import psycopg2 with psycopg2.connect("host='192.168.29.118' dbname='testdb' user='testuser1' password='test1234'") as connection: with connection.cursor() as cursor: cursor.execute("SELECT * FROM test;") resultList = cursor.fetchall() for result in resultList: print(result) """ (1, '홍길동', 20) (2, '김철수', 30) (3, '이영희', 25) """ |
▶ requirements.txt
1 2 3 |
psycopg2-binary==2.9.9 |