How Python manipulates data using DbUtil
Editor to share with you how Python uses DbUtil to operate data, I believe most people do not know much about it, so share this article for your reference, I hope you can learn a lot after reading this article, let's go to know it!
1.DbUtil operation class
#! / usr/bin/python
Import pymysql
''
Database operation class
''
Class DbUtil:
Dbconnect = None
Hostname =''
Username =''
Password =''
Dbname =''
Def _ init__ (self,hostname,username,password,dbname):
Self.hostname = hostname
Self.username = username
Self.password = password
Self.dbname = dbname
''
Get mysql connection object
''
Def open_connect (self):
Try:
# create a database connection
Self.dbconnect = pymysql.connect (self.hostname,self.username,self.password,self.dbname)
Except:
Print ('Open connection exception')
''
Data add operation
''
Def insert_data (self,sql):
# obtain operation cursors using the cursor () method
Cursor = self.dbconnect.cursor ()
Try:
# execute sql statement
Cursor.execute (sql)
# submit to the database for execution
Self.dbconnect.commit ()
Last_id = self.get_last_insert_id (cursor)
Cursor.close ()
Return last_id
Except:
# Roll back if an error occurs
Self.dbconnect.rollback ()
Print ('Please check whether the sql syntax is correct')
Return 0
''
Get the self-increment ID after the data is added successfully
''
Def get_last_insert_id (self,cursor):
Sql = 'SELECT LAST_INSERT_ID () AS id;'
Cursor.execute (sql)
Database = cursor.fetchone ()
Return database [0]
''
Query single piece of data
''
Def find_one (self,sql):
# obtain operation cursors using the cursor () method
Cursor = self.dbconnect.cursor ()
Try:
# execute SQL statement
Cursor.execute (sql)
# get a list of all records
Results = cursor.fetchone ()
Cursor.close ()
Return results
Except:
Print ("Error: unable to fetch data")
Return None
''
Close the database connection
''
Def close_connect (self):
If self.dbconnect! = None:
Self.dbconnect.close ()
Screenshot of 2.DbUtil class
3. Use the DbUtil class
#! / usr/bin/python
From DbUtil import DbUtil
From RegionModel import RegionModel
DbUtil = DbUtil ("localhost", "root", "", "enquiry")
RegionModel = RegionModel (dbUtil)
Region = regionModel.getAreaCode ()
Print (region [0])
The above is all the contents of the article "how Python uses DbUtil to manipulate data". Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!