Python operations on the mysql database, pythonmysql Database
#-*-Coding: UTF-8-*-from pymysql import connect, cursorsfrom pymysql. err import OperationalErrorimport osimport configparser as cparserfrom time import strftime, gmtime #========= read db_config.ini File Settings === base_dir = str (OS. path. dirname (OS. path. abspath (_ file _) # returns the absolute path base_dir = base_dir.replace ('\', '/') of The py script # str. replace (old, new [, max]) replaces the old string with the new string file_path = base_dir + "/db_config.ini" cf = cparser. configParser () # ConfigParser is the package used to read the configuration file. You must instantiate cf before using it. read (file_path) host = cf. get ("mysqlconf", "host") port = cf. get ("mysqlconf", "port") db = cf. get ("mysqlconf", "db_name") user = cf. get ("mysqlconf", "user") password = cf. get ("mysqlconf", "password") #======= encapsulate basic mysql operations ============= class DB: def _ init _ (self): # connect to the database try: self. conn = connect (host = host, user = user, port = int (port), password = password, db = db, charset = 'utf8mb4', cursorclass = cursors. dictCursor) failed t OperationalError as e: print ("mysql Error % d: % s" % (e. args [0], e. args [1]) # clear the database def clear (self, table_name): real_ SQL = "truncate table" + table_name + "; "# real_ SQL =" delete from "+ table_name +"; "with self. conn. cursor () as cursor: cursor.exe cute ("SET FOREIGN_KEY_CHECKS = 0;") # If a foreign key constraint is SET between the table and the table in Mysql, the table cannot be deleted or the table structure cannot be modified, the statement is used to cancel the foreign key constraint cursor.exe cute (real_ SQL) # execute the statement self. conn. commit () # If no commit is used, the data will not be retained in the database # insert data def insert (self, table_name, table_data): for key in table_data: table_data [key] = "'" + str (table_data [key]) + "'" key = ','. join (table_data.keys () value = ','. join (table_data.values () real_ SQL = "insert into" + table_name + "(" + key + ") VALUES (" + value + ")" print (real_ SQL) with self. conn. cursor () as cursor: cursor.exe cute (real_ SQL) self. conn. commit () # close the database connection def close (self): self. conn. close ()
Considering the frequent operations on the database, consider encapsulating basic operations.