forked from techstay/python-study
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpostgresql.py
More file actions
60 lines (48 loc) · 1.69 KB
/
postgresql.py
File metadata and controls
60 lines (48 loc) · 1.69 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
import psycopg2
import datetime
host = 'localhost'
username = 'postgres'
password = '12345678'
db_name = 'test'
create_table_sql = '''
CREATE TABLE author (
id SERIAL PRIMARY KEY,
name VARCHAR(30) NOT NULL,
birthday DATE
)
'''
insert_table_sql = '''
INSERT INTO author(name,birthday)VALUES (%s,%s)
'''
select_table_sql = '''SELECT * FROM author'''
select_one_sql = '''SELECT * FROM author WHERE name = %s'''
drop_table_sql = '''DROP TABLE author'''
connection = psycopg2.connect(host=host, user=username, password=password, dbname=db_name)
# 设置自动提交
connection.autocommit = True
try:
with connection.cursor() as cursor:
print('--------------新建表--------------')
cursor.execute(create_table_sql)
print('--------------插入数据--------------')
cursor.execute(insert_table_sql, ('易天', '1994-05-06'))
cursor.execute(insert_table_sql, ('张三', '1995-06-06'))
cursor.execute(insert_table_sql, ('李四', '1993-11-06'))
cursor.execute(insert_table_sql, ('王五', datetime.date.today()))
print('--------------显示数据--------------')
cursor.execute(select_table_sql)
results = cursor.fetchall()
print(f'id\tname\tbirthday')
for row in results:
print(row[0], row[1], row[2], sep='\t')
print('--------------查询数据--------------')
cursor.execute(select_one_sql, ('易天',))
results = cursor.fetchall()
print(f'id\tname\tbirthday')
for row in results:
print(row[0], row[1], row[2], sep='\t')
finally:
cursor = connection.cursor()
cursor.execute(drop_table_sql)
cursor.close()
connection.close()