Python_MySQL數據庫的寫入與讀取


【需求】1. 在數據庫中創建表,且能按時間自動創建新表 2. 數據寫入數據庫 3. 從數據庫讀取數據

1. 創建表,並自動更新

 1 def Creat_Table(InitMySQL,tabel_name):
 2     # 創建游標
 3     cursor = InitMySQL.cursor()
 4     sql = "create table if not exists " +  tabel_name  + "(dTime   datetime not null comment '時間'," \
 5                                                 "dElectric_uA  int not null comment '電流'," \
 6                                                 "dDistance   int not null comment '距離'," \
 7                                                 "dWarning    int not null comment '報警')"
 8     # 打印sql
 9     print(sql)
10     cursor.execute(sql)
11     # 關閉游標
12     cursor.close()

需要輸入數據庫的連接對象和表名稱,sql根據表名稱判斷數據庫中是否存在該表,如果存在則不會創建,不存在則創建新表

tabel_name 可以根據時間創建

2. 向數據庫中寫入數據

根據創建的數據庫中表的類型進行數據填充

 1 def Write_to_MySQL(InitMySQL,tabel_name, CurrentTime, Electric_uA, Distance, WaringStatus):
 2     # 創建游標
 3     cursor = InitMySQL.cursor()
 4     # #創建sql
 5     # w_table_name = 'warning' + day_time
 6     sql = 'insert into '+ tabel_name+ ' values (%s, %s, %s, %s)'
 7     print(sql)
 8     result = cursor.execute(sql,(CurrentTime, Electric_uA, Distance, WaringStatus))
 9     if result == 1:
10         pass
11         # print('添加成功!')
12     else:
13         print('添加數據失敗!')
14     # 4. 操作成功提交事務
15     InitMySQL.commit()
16     # 關閉游標
17     cursor.close()

整體表的創建與數據輸入

 1 import time
 2 import datetime
 3 import json
 4 import pymysql
 5 
 6 # JSON 文件初始化
 7 def InitJSON():
 8     global filejson
 9     try:
10         with open('TIE_LDY_20190923_1502.json', 'r') as f:
11             filejson = json.load(f)
12     except FileNotFoundError:
13         print('無法打開指定的文件!')
14     except LookupError:
15         print('指定了未知的編碼!')
16     except UnicodeDecodeError:
17         print('讀取文件時解碼錯誤!')
18 
19 #  數據庫參數初始化
20 def MysqlInit():
21     # global LiuCaoSQL
22     # 1. 創建數據庫連接對象
23     InitMySQL = pymysql.connect(host=filejson['MysqlInit']['host'], port=filejson['MysqlInit']['port'],
24                           database=filejson['MysqlInit']['database'], charset=filejson['MysqlInit']['charset'],
25                           user=filejson['MysqlInit']['user'], password=filejson['MysqlInit']['password'])
26     return InitMySQL
27 
28 def Creat_Table(InitMySQL,tabel_name):
29     # 創建游標
30     cursor = InitMySQL.cursor()
31     # # 獲取當前時間 年-月-日
32     # day_time = datetime.datetime.now().strftime("%Y_%m_%d_%H_%M")
33     # # 拼接table名稱
34     # tabel_name = 'warning' + day_time
35     # 創建sql語句  創建列表的表頭 注意表的類型create table if not exists tablename
36     sql = "create table if not exists " +  tabel_name  + "(dTime   datetime not null comment '時間'," \
37                                                 "dElectric_uA  int not null comment '電流'," \
38                                                 "dDistance   int not null comment '距離'," \
39                                                 "dWarning    int not null comment '報警')"
40     # 打印sql
41     print(sql)
42     cursor.execute(sql)
43     # 關閉游標
44     cursor.close()
45 
46 
47 # 向數據庫寫入內容
48 def Write_to_MySQL(InitMySQL,tabel_name, CurrentTime, Electric_uA, Distance, WaringStatus):
49     # 創建游標
50     cursor = InitMySQL.cursor()
51     # 獲取當前時間 年-月-日
52     # day_time = datetime.datetime.now().strftime("%Y_%m_%d_%H_%M")
53     # #創建sql
54     # w_table_name = 'warning' + day_time
55     sql = 'insert into '+ tabel_name+ ' values (%s, %s, %s, %s)'
56     print(sql)
57     result = cursor.execute(sql,(CurrentTime, Electric_uA, Distance, WaringStatus))
58     if result == 1:
59         pass
60         # print('添加成功!')
61     else:
62         print('添加數據失敗!')
63     # 4. 操作成功提交事務
64     InitMySQL.commit()
65     # 關閉游標
66     cursor.close()
67 def main():
68     # 初始化JSON 和數據庫
69     InitJSON()
70     InitMySQL = MysqlInit()
71     # 測試數據庫創建 表
72     # Creat_Table(InitMySQL)
73     # 測試寫入數據
74     Electric_uA = 1000
75     Distance = 1000
76     WaringStatus = 0
77     i= 0
78     while(i < 10000):
79         # 獲取當前時間 年-月-日
80         day_time = datetime.datetime.now().strftime("%Y_%m_%d_%H_%M")
81         # 拼接table名稱
82         tabel_name = 'warning' + day_time
83         # 測試數據庫創建 表
84         Creat_Table(InitMySQL,tabel_name)
85         i += 1
86         CurrentTime = datetime.datetime.now().strftime("%Y_%m_%d %H:%M:%S")
87         Electric_uA -= 1
88         Distance += 1
89         Write_to_MySQL(InitMySQL, tabel_name, CurrentTime, Electric_uA, Distance, WaringStatus)
90         time.sleep(0.01)
View Code

測試的數據庫結果:

 

 3. 從數據庫讀取數據

 1 """
 2    【函數功能】 讀取數據庫中最新的幾分鍾數據
 3    【輸入】     需要查詢的table名稱(也可以從JSON中讀取)
 4    【輸出】     查找的數據列表
 5 """
 6 def Read_from_Mysql(InitMySQL, sql_tabel_name):
 7     # 從JSON中讀取sql需要的參數
 8     set_time = filejson['MysqlInit']['set_delaytime_min']
 9     now_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
10     last_time = (datetime.datetime.now() - datetime.timedelta(minutes = set_time)).strftime("%Y-%m-%d %H:%M:%S")
11     # sql_tabel_name = filejson['MysqlInit']['sql_tabel_name']
12     sql_distance_header = filejson['MysqlInit']['distance_header']
13     sql_time_header = filejson['MysqlInit']['time_header']
14     # 創建游標
15     cursor = InitMySQL.cursor()
16     sql = "SELECT " + sql_distance_header + " FROM " + sql_tabel_name + " WHERE " + sql_time_header \
17           + "<'" + now_time + "'" + " and " +  sql_time_header + ">'" +last_time + "'"
18     # print(sql)
19     cursor.execute(sql)
20     # 獲取該字段下的數據
21     result = cursor.fetchall()
22     # 關閉游標
23     cursor.close()
24     # 將數據轉換成列表
25     new_distance= []
26     for dis in result:
27         new_distance.append(dis[0])
28     return new_distance

【重點】sql的字符串拼接中可以加入變量 時間需要用單引號引起來

 

 園中有博主寫的關於數據庫,非常詳細 可以參考 https://www.cnblogs.com/hackerer/p/11588717.html


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM