#-*- coding: utf-8 -*-
'''
======================================================================
:python Mysql , SQL ,
。
:xiawp
:2019/1/25 0:25
:python Mysql ,3.0+ pip3 pyMysql 。
pymysql.connect() ;
db cursor() ;
execute() sql;
fetchone() , None
fetchone() (List )
======================================================================
'''
import os
import time
import pymysql
rootdir = "D:/test"
# SQL
def executeSQL(sql):
dataList = []
#
db = pymysql.connect(host="localhost",
user="test",
password="1234",
port=3306,
database="testdb",
charset="utf8")
# cursor() cursor
cursor = db.cursor()
try:
printLog(" SQL:" + sql)
# execute() SQL
cursor.execute(sql)
except Exception as e:
printLog("SQL :" + sql)
printLog(str(e))
else:
# fetchall()
dataList = cursor.fetchall()
# dataList = cursor.fetchone() #
finally:
#
cursor.close()
db.close()
return dataList
# end def
#
def printLog (logMsg):
#
logPath = os.path.join(rootdir , "logs")
if not os.path.exists(logPath):
os.makedirs(logPath)
#
now = time.localtime(time.time())
logName = "".join(["log_", time.strftime("%Y%m%d", now), ".txt"])
logPath = os.path.join(logPath, logName)
formatDate = time.strftime("%Y-%m-%d %H:%M:%S", now)
messge = "".join(["== log message ", "[",formatDate,"]", " : \t", logMsg])
print (messge)
#
logfile = open(logPath,'a')
logfile.writelines(messge)
logfile.writelines("
")
logfile.close
#end def
# SQL
dataList = executeSQL("select * from city")
for i in range(len(dataList)):
print (dataList[i])
'''
EditPlus python37:
------------------------------------------------------------------------------------------------------------------------
---------- EditPlus Python37 ----------
== log message [2019-01-25 00:40:44] : SQL:select * from city
(1, ' ', 3)
(1, ' ', 32)
(1, ' ', 21)
(1, ' ', 1)
(1, ' ', 11)
(1, ' ', 29)
(1, ' ', 15)
(1, ' ', 7)
(1, ' ', 13)
(1, ' ', 33)
(1, ' ', 10)
(1, ' ', 2)
(1, ' ', 6)
(1, ' ', 20)
(1, ' ', 22)
(1, ' ', 30)
(1, ' ', 26)
(1, ' ', 12)
(1, ' ', 18)
(1, ' ', 8)
(1, ' ', 16)
(1, ' ', 25)
(1, ' ', 34)
(1, ' ', 5)
(1, ' ', 14)
(1, ' ', 27)
(1, ' ', 28)
(1, ' ', 24)
(1, ' ', 17)
(1, ' ', 4)
(1, ' ', 31)
(1, ' ', 9)
(1, ' ', 19)
(1, ' ', 35)
( 0 ) -
------------------------------------------------------------------------------------------------------------------------
'''