SoFunction
Updated on 2024-10-29

python db class usage description

I'll cut to the chase, so let's get right to the code~

import pymysql
 
class DB:
 __host = 'localhost' # Server address
 __username = 'root' # Username
 __password = '' # Password
 __database = 'test' # Database
 __field = '*' # Query Fields
 __where = '' # Conditions
 __sql = False # Whether to return sql
 __join = '' # Joint tables
 __order = '' # Sort
 __limit = '' # Quantity
 
 # constructor, called when generating the object
 def __init__(self, table):
  try:
   # Open a database connection host, username, password, database
    = (self.__host, self.__username, self.__password, self.__database)
  except Exception as e:
   print(e)
   exit()
 
  # Use the cursor() method to create a cursor object cursor
   = ()
   = table
 
 # Deconstructor function, used when releasing an object
 def __del__(self):
  try:
   # Close the database connection
   ()
  except Exception as e:
   print(e)
 
 # Get the current sql statement
 def getSql(self):
  self.__sql = True
  return self
 
 # field
 def field(self, str):
  self.__field = str
  return self
 
 # Joint tables
 def join(self, table, where):
  self.__join = ' LEFT JOIN ' + table + ' ON ' + where + ' '
  return self
 
 # Conditions
 def where(self, param):
  self.__where = ' WHERE '
  if isinstance(param, list):
   for i in param:
    if isinstance(i[2], list):
     tmp = '('
     for j in i[2]:
      tmp += str(j) + ','
     tmp += ')'
     self.__where += '`' + i[0] + '` ' + i[1] + ' ' + tmp + ' AND '
    else:
     self.__where += '`' + i[0] + '` ' + i[1] + ' ' + str(i[2]) + ' AND '
   else:
    self.__where = self.__where[0:-4]
  else:
   self.__where += param
 
  return self
 
 # Sort
 def order(self, str):
  self.__order = ' ORDER BY ' + str
  return self
 
 # Quantity
 def limit(self, str):
  self.__limit = ' LIMIT ' + str
  return self
 
 # Increase
 def insert(self, dict):
  key = value = ''
  for k, v in ():
   key += '`' + k + '`,'
   value += '"' + v + '",'
 
  key = key[0:-1]
  value = value[0:-1]
 
  sql = 'INSERT INTO ' +  + ' (' + key + ') VALUES (' + value + ')'
  if self.__sql:
   return sql
 
  try:
   # Execute sql statements
   ret = (sql)
   # Submitted to database for execution
   ()
   return ret
  except Exception as e:
   # Rollback if an error occurs
   ()
   print(e)
   return 0
 
 # Delete
 def delete(self):
  if self.__where:
   sql = "DELETE FROM " +  + self.__where
   if self.__sql:
    return sql
 
   try:
    # Execute sql statements
    ret = (sql)
    # Submitted to database for execution
    ()
    return ret
   except Exception as e:
    # Rollback if an error occurs
    ()
    print(e)
    return 0
 
  else:
   raise BaseException('No conditions') # Throwing exceptions
 
 # Modify
 def update(self, dict):
  str = ''
  for k, v in ():
   str += '`' + k + '`="' + v + '",'
 
  str = str[0:-1]
  sql = 'UPDATE ' +  + ' SET ' + str
 
  if self.__where:
   sql += self.__where
  if self.__sql:
   return sql
 
  try:
   # Execute sql statements
   ret = (sql)
   # Submitted to database for execution
   ()
   return ret
  except Exception as e:
   # Rollback if an error occurs
   ()
   print(e)
   return 0
 
 # Query
 def select(self):
  sql = "SELECT " + self.__field + " FROM " + 
 
  if self.__join:
   sql += self.__join
 
  if self.__where:
   sql += self.__where
 
  if self.__order:
   sql += self.__order
 
  if self.__limit:
   sql += self.__limit
 
  if self.__sql:
   return sql
 
  # Execute SQL queries using the execute() method
  (sql)
 
  # Use the fetchall() method to get all the data.
  data = ()
  return data
'''
DROP TABLE IF EXISTS `people`;
CREATE TABLE `people` (
 `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
 `name` varchar(20) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NOT NULL COMMENT 'Name',
 `sex` varchar(7) DEFAULT '' COMMENT 'distinguishing between the sexes',
 `job` varchar(6) DEFAULT '' COMMENT '(of a machine) operate',
 `age` varchar(6) DEFAULT '' COMMENT '(a person's) age',
 `height` varchar(6) DEFAULT '' COMMENT '(a person's) height',
 `weight` varchar(6) DEFAULT '' COMMENT 'weight',
 PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;
INSERT INTO `people` VALUES ('1', 'Zhao Yi', 'Male', 'Students', '8', '120', '35');
INSERT INTO `people` VALUES ('2', 'Qian Er', 'Female', 'Students', '9', '111', '31');
INSERT INTO `people` VALUES ('3', 'Sun San', 'Male', 'Students', '10', '123', '34');
INSERT INTO `people` VALUES ('4', 'Li Si', 'Female', 'Students', '11', '100', '30');
'''
db = DB('people')
 
# Increase
dict = {'name': 'Friday', 'sex': 'Male', 'job': 'Students', 'age': '8', 'height': '121', 'weight': '32'}
data = (dict)
print(data)
 
# Delete
# data = ('id=6').delete()
# print(data)
 
# Modify
# dict = {'age': '9', 'height': '121', 'weight': '31'}
# data = ('id=7').update(dict)
# print(data)
 
# query optimize where condition 'id<11'
# data = ('id,name,age,job').where([['id', '>', 1]]).order('id desc').limit('3').select()
# print(data)

Additional knowledge:python DB API cursor Common Interfaces

1. description

If cursor executes the sql code for the query. Then reading the attributes will return a list of tuples that hold the

is (name,type_code,display_size,internal_size,precision,scale,null_ok), where name represents the name of the field where the data is found, and the other parameters are not very useful for the time being.

2. rowcount

represents the number of rows affected by the execution of the sql statement.

3. close

Close the cursor. The cursor should never be used again after it is closed, or an exception will be thrown.

4. execute(sql[,parameters])

Executes an sql statement. If you need to pass parameters when executing the sql statement, you can pass parameters. The example code is as follows:

("select * from article where id=%s",(1,))

5. fetchone

Fetches the first piece of data after the query operation has been performed.

6. fetchmany(size)

After the query is executed, multiple pieces of data are fetched. How many depends on the size parameter passed. If you don't pass the size parameter, then the default is to get the first data.

7. fetchall

Get all the data that satisfies the sql statement.

This python db class usage description above is all I have to share with you, I hope it will give you a reference, and I hope you will support me more.