-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtest4.py
40 lines (31 loc) · 1.1 KB
/
test4.py
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
import mysql.connector
from mysql.connector.errors import Error
from mysql_connection import get_connection
# 연결하는 코드
# try 라고 나오면, 들여쓰기 되어있는 문장들을 싱행하라는 뜻.
try :
connection = get_connection()
query = '''select *
from test
where id = %s;'''
param = (3,)
cursor = connection.cursor()
cursor.execute(query,param)
# select 문은 아래 내용이 필요하다.
record_list = cursor.fetchall()
print(record_list)
for row in record_list :
print('id =',row[0])
print('name =',row[1])
print('date =', row[2].isoformat())
# 위의 코드를 실행하다가, 문제가 생기면, except를 실행하라는 뜻.
except Error as e :
print('Error while connecting to MySQL',e)
# finally 는 try에서 에러가 나든 안나든, 무조건 실행하라는 뜻.
finally :
cursor.close()
if connection.is_connected():
connection.close()
print('MySQL connection is closed')
else:
print('connection does not exist')