-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdb
More file actions
executable file
·69 lines (59 loc) · 1.84 KB
/
Copy pathdb
File metadata and controls
executable file
·69 lines (59 loc) · 1.84 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
#!/usr/bin/env .venv/bin/python3
"""Tietokantakyselytyökalu — lukee kirjautumistiedot .env-tiedostosta.
Käyttö:
./db "SELECT * FROM Kurssi LIMIT 5"
./db "SHOW TABLES"
"""
import os
import sys
from pathlib import Path
import mysql.connector
from dotenv import load_dotenv
load_dotenv(Path(__file__).parent / ".env")
def _yhdista():
return mysql.connector.connect(
host=os.getenv("DB_HOST", "localhost"),
port=int(os.getenv("DB_PORT", 21212)),
user=os.getenv("DB_USER"),
password=os.getenv("DB_PASSWORD"),
database=os.getenv("DB_NAME"),
charset="utf8mb4",
)
def _tulosta(kursori) -> None:
if not kursori.description:
print(f"OK — {kursori.rowcount} riviä muutettu")
return
sarakkeet = [s[0] for s in kursori.description]
rivit = kursori.fetchall()
if not rivit:
print("(tyhjä tulos)")
return
leveydet = [len(s) for s in sarakkeet]
for rivi in rivit:
for i, solu in enumerate(rivi):
leveydet[i] = max(leveydet[i], len(str(solu) if solu is not None else "NULL"))
muoto = " | ".join(f"{{:<{l}}}" for l in leveydet)
print(muoto.format(*sarakkeet))
print("-+-".join("-" * l for l in leveydet))
for rivi in rivit:
print(muoto.format(*[str(s) if s is not None else "NULL" for s in rivi]))
print(f"\n({len(rivit)} rivi{'ä' if len(rivit) != 1 else ''})")
def main() -> None:
if len(sys.argv) < 2:
print(__doc__)
sys.exit(1)
sql = " ".join(sys.argv[1:])
yht = _yhdista()
kursori = yht.cursor()
try:
kursori.execute(sql)
_tulosta(kursori)
yht.commit()
except mysql.connector.Error as e:
print(f"Virhe: {e}", file=sys.stderr)
sys.exit(1)
finally:
kursori.close()
yht.close()
if __name__ == "__main__":
main()