Encapsulation of database tool classes.
Purpose of packaging:
- Encapsulate commonly used database operations into a method. When operating the database in the future, call this method to achieve
- Improve code reusability
Design database tool class.
Get Close Connection.
import pymysql
class DBUtil:
#define class attributes to address the issue of yellow reporting
conn = None
#linking databases
@classmethod
def __connect_db(cls):
cls.conn = pymysql.connect(host="211.103.136.244", port=7061, user="student", password="iHRM_student_2022",
database="test_db", charset="utf8")
return cls.conn
#close database
@classmethod
def __close_db(cls):
cls.conn.close() #class properties can directly call methods without prompting
#method of encapsulation reading
@classmethod
def query_db(cls, sql):
result = None
cursor = None
try:
#create a link to the database
cls.conn = cls.__connect_db()
#get cursor
cursor = cls.conn.cursor()
#implement sql,return query results
cursor.execute(sql)
result = cursor.fetchone() #extract the first row
except Exception as err:
print("error reading database :", err)
finally:
#close cursor
cursor.close()
#close link
cls.__close_db()
return result
#methods for packaging, adding, deleting, and modifying
@classmethod
def update_db(cls, sql):
cursor = None
try:
#create a link to the database
cls.conn = cls.__connect_db()
#get cursor
cursor = cls.conn.cursor()
#implement sql print the number of affected rows
cursor.execute(sql)
affect_rows = cls.conn.affected_rows()
print("the number of rows affecting the database :", affect_rows)
#submission and rollback of transactions
cls.conn.commit()
except Exception as err:
#rollback of transactions
cls.conn.rollback()
print("add, delete, modify database error message :", err)
pass
finally:
#close cursor
cursor.close()
#close link
cls.__close_db()
if __name__== '__main__':
res1 = DBUtil.query_db("select * from t_book ;")
print(res1)
DBUtil.update_db("insert into t_book (id,title,pub_date) VALUES(1256345253,'iron man','2022-5-1');")
res2 = DBUtil.query_db("select * from t_book where id = 10145253 ;")
print(res2)
pass
```python
running results
(2, 'journey to the west', datetime.date(1980, 1, 1), 1, 0, 0)
the number of rows affecting the database : 1
(1255, 'iron man', datetime.date(2022, 5, 1), 0, 0, 0)