協助Python調用PostgreSQL資料庫的套件如下:
1. Psycopg
安裝指令:
pip install psycopg2
建立資料表及插入資料
寫法一:
import psycopg2 #host='localhost'或host='DESKTOP-40IGE82' host = 'server name' dbname = 'database name' #dataname='postgre' user = 'admin username' #user='postgre' password = 'admin password' sslmode = 'require'
# Construct connection string conn_string = 'host={} user={} password={} sslmode={}'.format(host, user, dbname, password, sslmode) conn = psycopg2.connect(conn_string) print('Connection Established~')
cursor = conn.cursor()
# Drop previous table of same name if one exists cursor.execute('DROP TABLE IF EXISTS inventory;') print('Finished dropping table (if existed)')
# Create a table cursor.execute("CREATE TABLE inventory (id serial PRIMARY KEY, name VARCHAR(50), quantity INTEGER);") print('Finished creating table')
# Insert some data into the table cursor.execute("INSERT INTO inventory (name, quantity) VALUES (%s, %s);", ("banana", 150)) cursor.execute("INSERT INTO inventory (name, quantity) VALUES (%s, %s);", ("orange", 154)) cursor.execute("INSERT INTO inventory (name, quantity) VALUES (%s, %s);", ("apple", 100)) print('Inserted 3 rows of data')
#Clean up conn.commit() cursor.close() conn.close() |
寫法二:
import psycopg2 # Create connect conn = psycopg2.connect(database='postgre', host='localhost', port='1234', user='postgre', password='12345678') cursor = conn.cursor() # Create a table cursor.execute("CREATE TABLE inventory (id serial PRIMARY KEY, name VARCHAR(50), quantity INTEGER);") print('Finished creating table') # Insert some data into the table cursor.execute("INSERT INTO inventory (name, quantity) VALUES (%s, %s);", ("banana", 150)) cursor.execute("INSERT INTO inventory (name, quantity) VALUES (%s, %s);", ("orange", 154)) cursor.execute("INSERT INTO inventory (name, quantity) VALUES (%s, %s);", ("apple", 100)) print('Inserted 3 rows of data')
# search data information cursor.execute("SELECT * FROM inventory") results = cursor.fetchall() print(results)
#Clean up conn.commit() cursor.close() conn.close() |
留言列表