-
Notifications
You must be signed in to change notification settings - Fork 49
/
mysql_basic_demo.py
78 lines (65 loc) · 2.36 KB
/
mysql_basic_demo.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
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
70
71
72
73
74
75
76
77
78
# -*- coding: utf8 -*-
import datetime
import pymysql.cursors
import logging
import sys
import pytz
# MySql database account information, you need to create a database in advance. MySql数据库账号信息,需要提前创建好数据库
Host = '******'
User = '****'
Password = '****'
Port = 63054
DB = u'SCF_Demo'
logging.basicConfig(level=logging.INFO, stream=sys.stdout)
logger = logging.getLogger()
logger.setLevel(level=logging.INFO)
# Changing the time zone to Beijing. 更改时区为北京时区
tz = pytz.timezone('Asia/Shanghai')
g_connection = None
g_connection_errno = 0
def connect_mysql():
global g_connection
global g_connection_errno
try:
g_connection = pymysql.connect(host=Host,
user=User,
password=Password,
port=Port,
db=DB,
charset='utf8',
cursorclass=pymysql.cursors.DictCursor)
except Exception as e:
g_connection = None
g_connection_errno = e[0]
print("connect database error:%s"%e)
print("connect database")
connect_mysql()
def main_handler(event, context):
print('Start function')
print("{%s}" % datetime.datetime.now(tz).strftime("%Y-%m-%d %H:%M:%S"))
print("g_connection is %s" % g_connection)
if not g_connection:
connect_mysql()
if not g_connection:
return {"code": 409, "errorMsg": "internal error %s" % g_connection_errno}
with g_connection.cursor() as cursor:
sql = 'show databases'
cursor.execute(sql)
res = cursor.fetchall()
print res
sql = 'use %s'%DB
cursor.execute(sql)
# Creating a data table. 创建数据表
cursor.execute("DROP TABLE IF EXISTS Test")
cursor.execute("CREATE TABLE Test (Msg TEXT NOT NULL,Time Datetime)")
time = datetime.datetime.now(tz).strftime("%Y-%m-%d %H:%M:%S")
sql = "insert INTO Test (`Msg`, `Time`) VALUES (%s, %s)"
cursor.execute(sql, ("test", time))
g_connection.commit()
sql = "select count(*) from Test"
cursor.execute(sql)
result = cursor.fetchall()
print(result)
cursor.close()
print("{%s}" % datetime.datetime.now(tz).strftime("%Y-%m-%d %H:%M:%S"))
return "test"