-
Notifications
You must be signed in to change notification settings - Fork 4
postgres python psycopg2
ghdrako edited this page Dec 4, 2024
·
2 revisions
import psycopg2
conn = psycopg2.connect(
database="postgres",
host="localhost",
port="5432",
user="postgres",
password=""
)
cursor = conn.cursor()
cursor.execute("CREATE TABLE t1 (a int, b int)")
cursor.execute("INSERT INTO t1 values (1,2)")
cursor.execute("INSERT INTO t1 values (4,5)")
cursor.execute("INSERT INTO t1 values (6,7)")
cursor.execute("INSERT INTO t1 values (7,8)")
nums = [(1,2),(3,4),(5,6),(7,8)]
cursor.executemany("INSERT INTO t1 values (%s,%s)",nums)
returns a single row from an executed query.
nums = [(1,2),(3,4),(5,6),(7,8)]
cursor.executemany("INSERT INTO t1 values (%s,%s)",nums)
cursor.execute("select * from t1")
print(cursor.fetchone())
The output of this will be
(1, 2)
If we were to run multiple fetchone()
functions, each call would return the next row as the previous is consumed.
get all rows
nums = [(1,2),(3,4),(5,6),(7,8)]
cursor.executemany("INSERT INTO t1 values (%s,%s)",nums)
cursor.execute("select * from t1")
print(cursor.fetchall())
Output
[(1, 2), (3, 4), (5, 6), (7, 8)]
get a specified amount of rows returned from a query
nums = [(1,2),(3,4),(5,6),(7,8)]
cursor.executemany("INSERT INTO t1 values (%s,%s)",nums)
cursor.execute("select * from t1")
print(cursor.fetchmany(size=2))
[(1, 2), (3, 4)]
Test