pylhb 0.2.1__tar.gz → 0.2.3__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.3
2
2
  Name: pylhb
3
- Version: 0.2.1
3
+ Version: 0.2.3
4
4
  Summary: Mr.Lee's Helpers
5
5
  License: Non-Commercial Use License
6
6
 
@@ -56,8 +56,6 @@ if __name__ == "__main__":
56
56
  (successed,msg)=mssql.connect()
57
57
  # print(successed)
58
58
  # print(msg)
59
- print("数据库连接是否成功:")
60
- print(mssql.Connected)
61
59
 
62
60
  # Demo1:查询数据
63
61
  sql="SELECT TOP 2 P_CusName,P_Tel FROM Dt_Customers WITH(NOLOCK)"
@@ -122,3 +120,94 @@ if __name__ == "__main__":
122
120
  config.set("main", "host", "127.0.0.1")
123
121
  print(config.get("main", "host"))
124
122
  ```
123
+
124
+ ## 🌺mysqlite
125
+
126
+ 通过sqlite3访问SQLite数据库。
127
+
128
+ 使用示例:
129
+
130
+ ```
131
+ if __name__ == "__main__":
132
+ # 创建数据库实例
133
+ db = SQLite("test.db")
134
+
135
+ # 连接数据库
136
+ db.connect()
137
+
138
+ # 创建表
139
+ columns = {
140
+ "id": "INTEGER PRIMARY KEY AUTOINCREMENT",
141
+ "name": "TEXT NOT NULL",
142
+ "age": "INTEGER",
143
+ "email": "TEXT"
144
+ }
145
+ db.createTable("users", columns)
146
+
147
+ # 插入数据
148
+ user1 = {"name": "张三", "age": 25, "email": "zhangsan@example.com"}
149
+ user2 = {"name": "李四", "age": 30, "email": "lisi@example.com"}
150
+ user3 = {"name": "王五", "age": 28, "email": "wangwu@example.com"}
151
+
152
+ db.insert("users", user1)
153
+ db.insert("users", user2)
154
+ db.insert("users", user3)
155
+
156
+ # 查询所有数据
157
+ print("所有用户:")
158
+ users = db.select("users")
159
+ for user in users:
160
+ print(user)
161
+
162
+ # 条件查询
163
+ print("\n年龄大于28的用户:")
164
+ users = db.select("users", where="age > ?", params=(28,))
165
+ for user in users:
166
+ print(user)
167
+
168
+ # 更新数据
169
+ update_data = {"age": 31}
170
+ db.update("users", update_data, "name = ?", ("李四",))
171
+
172
+ # 查询特定列
173
+ print("\n用户姓名和邮箱:")
174
+ users = db.select("users", columns=["name", "email"])
175
+ for user in users:
176
+ print(user)
177
+
178
+ # 删除数据
179
+ db.delete("users", "name = ?", ("王五",))
180
+
181
+ # 再次查询所有数据
182
+ print("\n删除后的所有用户:")
183
+ users = db.select("users")
184
+ for user in users:
185
+ print(user)
186
+
187
+ # 关闭连接
188
+ db.close()
189
+ ```
190
+
191
+ ## 🌺mylog
192
+
193
+ 本地日志操作。
194
+
195
+ 使用示例:
196
+
197
+ ```
198
+ if __name__ == "__main__":
199
+ myLog= MyLog()
200
+ myLog.add("This is a test log entry.")
201
+ ```
202
+
203
+ ## 🌺myjson
204
+
205
+ json配置操作
206
+
207
+ 使用示例:
208
+
209
+ ```
210
+ if __name__ == "__main__":
211
+ appJson = MyJSON("config.json")
212
+ print(appJson.get("host"))
213
+ ```
@@ -23,8 +23,6 @@ if __name__ == "__main__":
23
23
  (successed,msg)=mssql.connect()
24
24
  # print(successed)
25
25
  # print(msg)
26
- print("数据库连接是否成功:")
27
- print(mssql.Connected)
28
26
 
29
27
  # Demo1:查询数据
30
28
  sql="SELECT TOP 2 P_CusName,P_Tel FROM Dt_Customers WITH(NOLOCK)"
@@ -89,3 +87,94 @@ if __name__ == "__main__":
89
87
  config.set("main", "host", "127.0.0.1")
90
88
  print(config.get("main", "host"))
91
89
  ```
90
+
91
+ ## 🌺mysqlite
92
+
93
+ 通过sqlite3访问SQLite数据库。
94
+
95
+ 使用示例:
96
+
97
+ ```
98
+ if __name__ == "__main__":
99
+ # 创建数据库实例
100
+ db = SQLite("test.db")
101
+
102
+ # 连接数据库
103
+ db.connect()
104
+
105
+ # 创建表
106
+ columns = {
107
+ "id": "INTEGER PRIMARY KEY AUTOINCREMENT",
108
+ "name": "TEXT NOT NULL",
109
+ "age": "INTEGER",
110
+ "email": "TEXT"
111
+ }
112
+ db.createTable("users", columns)
113
+
114
+ # 插入数据
115
+ user1 = {"name": "张三", "age": 25, "email": "zhangsan@example.com"}
116
+ user2 = {"name": "李四", "age": 30, "email": "lisi@example.com"}
117
+ user3 = {"name": "王五", "age": 28, "email": "wangwu@example.com"}
118
+
119
+ db.insert("users", user1)
120
+ db.insert("users", user2)
121
+ db.insert("users", user3)
122
+
123
+ # 查询所有数据
124
+ print("所有用户:")
125
+ users = db.select("users")
126
+ for user in users:
127
+ print(user)
128
+
129
+ # 条件查询
130
+ print("\n年龄大于28的用户:")
131
+ users = db.select("users", where="age > ?", params=(28,))
132
+ for user in users:
133
+ print(user)
134
+
135
+ # 更新数据
136
+ update_data = {"age": 31}
137
+ db.update("users", update_data, "name = ?", ("李四",))
138
+
139
+ # 查询特定列
140
+ print("\n用户姓名和邮箱:")
141
+ users = db.select("users", columns=["name", "email"])
142
+ for user in users:
143
+ print(user)
144
+
145
+ # 删除数据
146
+ db.delete("users", "name = ?", ("王五",))
147
+
148
+ # 再次查询所有数据
149
+ print("\n删除后的所有用户:")
150
+ users = db.select("users")
151
+ for user in users:
152
+ print(user)
153
+
154
+ # 关闭连接
155
+ db.close()
156
+ ```
157
+
158
+ ## 🌺mylog
159
+
160
+ 本地日志操作。
161
+
162
+ 使用示例:
163
+
164
+ ```
165
+ if __name__ == "__main__":
166
+ myLog= MyLog()
167
+ myLog.add("This is a test log entry.")
168
+ ```
169
+
170
+ ## 🌺myjson
171
+
172
+ json配置操作
173
+
174
+ 使用示例:
175
+
176
+ ```
177
+ if __name__ == "__main__":
178
+ appJson = MyJSON("config.json")
179
+ print(appJson.get("host"))
180
+ ```
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "pylhb"
3
- version = "0.2.1"
3
+ version = "0.2.3"
4
4
  description = "Mr.Lee's Helpers"
5
5
  readme = "README.md"
6
6
  license = {file = "LICENSE"}
@@ -0,0 +1,28 @@
1
+ """
2
+ 模块:myjson
3
+ 作者:李生
4
+ """
5
+ import json
6
+
7
+ # JSON读写
8
+ class MyJSON:
9
+ # 构造函数
10
+ def __init__(self,jsonFile="config.json") -> None:
11
+ self.jsonFile=jsonFile
12
+
13
+ # 获取Key
14
+ def getKey(self,key):
15
+ with open(self.jsonFile,'r', encoding="utf-8") as f:
16
+ configs=json.load(f)
17
+ return configs[key]
18
+
19
+ # 设置Key
20
+ def setKey(self,key,value):
21
+ # 读取
22
+ with open(self.jsonFile,'r', encoding="utf-8") as f:
23
+ configs=json.load(f)
24
+ # 设置参数
25
+ configs[key]=value
26
+ # 保存
27
+ with open(self.jsonFile, 'w', encoding="utf-8") as f:
28
+ json.dump(configs, f)
@@ -0,0 +1,52 @@
1
+ """
2
+ 模块:mylog
3
+ 作者:李生
4
+ """
5
+ import os
6
+ from datetime import datetime
7
+ import inspect
8
+
9
+ # 日志处理类
10
+ class MyLog:
11
+ # 初始化
12
+ # 注意:保留天数(retainDays)必须在toLogFolder=True时才有效
13
+ def __init__(self, logType="Log", logFile='',toLogFolder=True,retainDays=30):
14
+ self.logType = logType
15
+ if len(self.logType)==0:
16
+ self.logType = "Log"
17
+ self.logFile= logFile
18
+ if len(self.logFile) == 0:
19
+ self.logFile=self.getTodayFileName()
20
+ self.toLogFolder = toLogFolder
21
+ self.retainDays = retainDays
22
+ if toLogFolder:
23
+ if not os.path.exists("Logs"):
24
+ os.makedirs("Logs")
25
+
26
+
27
+ # 获取今天的日志文件名
28
+ def getTodayFileName(self):
29
+ if self.toLogFolder:
30
+ return os.path.join("Logs", self.logType + "-" + datetime.now().strftime("%Y-%m-%d") + ".txt")
31
+ else:
32
+ return self.logType + "-" + datetime.now().strftime("%Y-%m-%d") + ".txt"
33
+
34
+ # 删除过期日志
35
+ def deleteExpiredLogs(self):
36
+ if self.toLogFolder:
37
+ logDir = "Logs"
38
+ if os.path.exists(logDir):
39
+ for filename in os.listdir(logDir):
40
+ filePath = os.path.join(logDir, filename)
41
+ if os.path.isfile(filePath):
42
+ fileDate = datetime.strptime(filename.split('-')[1].split('.')[0], "%Y-%m-%d")
43
+ if (datetime.now() - fileDate).days > self.retainDays:
44
+ os.remove(filePath)
45
+
46
+ # 添加日志
47
+ def add(self,log):
48
+ callFrame = inspect.currentframe().f_back
49
+ callInfo = inspect.getframeinfo(callFrame)
50
+ with open(self.logFile, 'a', encoding='utf-8') as file:
51
+ file.write(datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f")[:-3] + " => " + f"{callInfo.filename} > {callInfo.function} > {callInfo.lineno}行" + ":" + log + "\n")
52
+
@@ -0,0 +1,102 @@
1
+ """
2
+ 模块:mysqlite
3
+ 作者:李生
4
+ """
5
+ import sqlite3
6
+ from typing import List, Tuple, Any, Optional
7
+
8
+ class SQLite:
9
+ def __init__(self, dbName: str = "data.db"):
10
+ self.dbName = dbName
11
+ self.connection = None
12
+ self.cursor = None
13
+
14
+ # 连接数据库
15
+ def connect(self) -> tuple[bool,str]:
16
+ try:
17
+ self.connection = sqlite3.connect(self.dbName)
18
+ self.cursor = self.connection.cursor()
19
+ return True,"OK"
20
+ except sqlite3.Error as e:
21
+ return False,str(e)
22
+
23
+ # 创建表
24
+ def createTable(self, tableName: str, columns: dict) -> tuple[bool,str]:
25
+ if not self.connection:
26
+ self.connect()
27
+ cols = ", ".join([f"{name} {defn}" for name, defn in columns.items()])
28
+ sql = f"CREATE TABLE IF NOT EXISTS {tableName} ({cols})"
29
+ try:
30
+ self.cursor.execute(sql)
31
+ self.connection.commit()
32
+ return True,"OK"
33
+ except sqlite3.Error as e:
34
+ return False,str(e)
35
+
36
+ # 插入记录
37
+ def insert(self, tableName: str, data: dict) -> tuple[bool,Optional[int]]:
38
+ if not self.connection:
39
+ self.connect()
40
+ columns = ", ".join(data.keys())
41
+ placeholders = ", ".join(["?"] * len(data))
42
+ values = tuple(data.values())
43
+ sql = f"INSERT INTO {tableName} ({columns}) VALUES ({placeholders})"
44
+ try:
45
+ self.cursor.execute(sql, values)
46
+ self.connection.commit()
47
+ return True,self.cursor.lastrowid
48
+ except sqlite3.Error as e:
49
+ return False,None
50
+
51
+ # 查询数据
52
+ def select(self, tableName: str, columns: List[str] = None, where: str = None, params: Tuple[Any] = None) -> tuple[bool,List[Tuple]]:
53
+ if not self.connection:
54
+ self.connect()
55
+ cols = "*" if columns is None else ", ".join(columns)
56
+ sql = f"SELECT {cols} FROM {tableName}"
57
+ if where:
58
+ sql += f" WHERE {where}"
59
+ try:
60
+ if where and params:
61
+ self.cursor.execute(sql, params)
62
+ else:
63
+ self.cursor.execute(sql)
64
+ results = self.cursor.fetchall()
65
+ return True,results
66
+ except sqlite3.Error as e:
67
+ return False,[]
68
+
69
+ # 更新数据
70
+ def update(self, tableName: str, data: dict, where: str, params: Tuple[Any]) -> tuple[bool,str]:
71
+ if not self.connection:
72
+ self.connect()
73
+ set_clause = ", ".join([f"{key} = ?" for key in data.keys()])
74
+ values = tuple(data.values()) + params
75
+ sql = f"UPDATE {tableName} SET {set_clause} WHERE {where}"
76
+ try:
77
+ self.cursor.execute(sql, values)
78
+ self.connection.commit()
79
+ return True,"OK"
80
+ except sqlite3.Error as e:
81
+ return False,str(e)
82
+
83
+ # 删除数据
84
+ def delete(self, tableName: str, where: str, params: Tuple[Any]) -> tuple[bool,str]:
85
+ if not self.connection:
86
+ self.connect()
87
+ sql = f"DELETE FROM {tableName} WHERE {where}"
88
+ try:
89
+ self.cursor.execute(sql, params)
90
+ self.connection.commit()
91
+ return True,"OK"
92
+ except sqlite3.Error as e:
93
+ return False,str(e)
94
+
95
+ # 关闭连接
96
+ def close(self) -> None:
97
+ if self.cursor:
98
+ self.cursor.close()
99
+ self.cursor=None
100
+ if self.connection:
101
+ self.connection.close()
102
+ self.connect=None
File without changes
File without changes
File without changes
File without changes