🐼
PostgreSQL Playground
Installment
- EDBのPosgtgreSQLパッケージからインストール
- Stack Builder
- 関連環境の構築
- EDB Language Pack
- PostgreSQL v15.1
- インストールした後、pdAdmin4を実行しようとするとエラーが出た
The application cannot be opened for an unexpected reason, error=Error Domain=NSOSStatusErrorDomain Code=-10669 "(null)" UserInfo={_LSLine=4101, _LSFunction=_LSOpenStuffCallLocal}
- Finderからアプリを見つけ出して、
情報→Rosettaを使用して開く
は有効(M1チップの問題?)
pgAdmin 4
- Add New Server
- General > Name: サーバー名
- Connection > Host name/address: サーバーアドレス
- Connection > Username: ユーザー名
- Connection > Password: ユーザーパスワード
- Server(右クリック)→CreateDatabase
- Database(右クリック)→QueryTool
SQL
- create table
create table t_user(
name varchar(32),
id char(10) NOT NULL PRIMARY KEY,
pwd varchar(128) NOT NULL
);
- insert table
INSERT INTO t_user VALUES(
'user1',
'1',
'test_1'
);
- select
SELECT *
FROM t_user
WHERE id='1';
Python - PostgreSQL
- psycopg2パッケージをインストール
pip install psycopg2-binary
- Datasetと繋ぐ
import psycopg2
connection = psycopg2.connect(
host='localhost',
user='postgres',
password= %PASSWORD%,
database='postgres_playground'
)
- データの挿入
name = 'user3'
id = 4
pwd = 'hello'
with connection:
with connection.cursor() as cursor:
sql = f"INSERT INTO t_user VALUES(%s, %s, %s);"
cursor.execute(sql, (name, id, pwd))
connection.commit()
- 複数のデータの挿入
users = [
['user4', 6, '0101'],
['user4', 7, '0101'],
]
with connection:
with connection.cursor() as cursor:
sql = f"INSERT INTO t_user VALUES(%s, %s, %s);"
cursor.executemany(sql, users)
connection.commit()
- データの取得
with connection:
with connection.cursor() as cursor:
sql = "SELECT * FROM t_user WHERE id=%s"
cursor.execute(sql, '2')
result = cursor.fetchone()
print(result)
- 複数データの取得
with connection:
with connection.cursor() as cursor:
sql = "SELECT * FROM t_user"
cursor.execute(sql)
result = cursor.fetchall()
print(result)
- 辞書型データの取得
from psycopg2.extras import DictCursor
dict_cursor = connection.cursor(cursor_factory=DictCursor)
with connection:
with dict_cursor:
sql = "SELECT * FROM t_user"
dict_cursor.execute(sql)
result = dict_cursor.fetchall()
print(result)
df = pd.DataFrame(result) # pandasとの互換性◎
- データの更新
with connection:
with connection.cursor() as cursor:
sql = "UPDATE t_user SET name=%s WHERE id=%s"
cursor.execute(sql, ("new_name", "1"))
connection.commit()
基本普通のSQLコマンドとして扱うことができ、入力も簡単。
Discussion