In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article introduces the relevant knowledge of "how to use Python to achieve the encapsulation of adding, deleting, changing and querying sqlite3". In the operation of the actual case, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!
Development background:
Every project has to write a database, which is annoying to death. And then every time the database takes a lot of time. I'm sick of it! It is better to write a general addition, deletion, check and change, in order not to change!
Properties:
Build a general addition, deletion, query and modification module to reduce the amount of code.
Make the code clearer and readable
Even if it is encapsulated, it does not affect its flexibility at all.
I won't introduce sqlite3 any more, just go to the code. Attach relevant usage and test cases!
Use the method import sqlite3''' to write a class to be packaged into a library, and the return value of the general sqlite' function for storing information can be optimized 'use: use' description: 1. Singleton mode to connect to the database: avoid database down 2 caused by too much database connect, and compare the performance of checking and modifying according to database additions, deletions and deletions. Uniformly use execute for general database operations 3, and do not do try operations: 1, affect performance 2, if an error is reported, the external call cannot determine the problem '' class LiteDb (object): _ instance = None def _ _ new__ (cls, * args, * * kw): if cls._instance is None: cls._instance = object.__new__ (cls) return cls._instance def openDb (self Dbname): self.dbname = dbname self.conn = sqlite3.connect (self.dbname) self.cursor = self.conn.cursor () def closeDb (self):''close the database: return:' 'self.cursor.close () self.conn.close () def createTables (self Sql):''example:'create table userinfo (name text, email text)': return: result= [1MagneNone]''self.cursor.execute (sql) self.conn.commit () result= [1MNone] return result def dropTables (self Sql):''example:'drop table userinfo': param sql:: return:result= [1MagneNone]' 'self.cursor.execute (sql) self.conn.commit () result= [1MagneNone] return result def executeSql (self, sql, value=None):' 'execute a single sql statement Just pass in the sql statement and value: param sql:'insert into user (name,password,number,status) values (?,?)' 'delete from user where name=?' 'updata user set status=? where name=?' 'select * from user where id=%s': param value: [(123456 value,list 123456), (123123123123)] value:'123456' value: (123123): return:result= [1rect none]' 'add, delete, check, change''if isinstance (value,list) and isinstance (value [0], (list) Tuple): for valu in value: self.cursor.execute (sql, valu) else: self.conn.commit () result = [1 Self.cursor.fetchall ()] else:''execute a single statement: string, integer, array''if value: self.cursor.execute (sql, value) else: self.cursor.execute (sql) self.conn.commit () result = [1 Self.cursor.fetchall ()] return result test case from dbUse import LiteDb''' tests the secondary encapsulated database to 'add, delete, query, modify', 'select name from sqlite_master where type='tableselect * from user'select * from user where id=% s'%7select * from user where id=?, 7select * from user where id=? Or id=?, [insert into user (id) values (7) 'insert into user (id) values (% s)'% 7'insert into user (id) values (?)', [('10,), ('11,)] delete from user where id=7'delete from user where id=%s'%7'delete from user where id=?', [('10,), ('11') )] update user set id=7 where id=11'update user set id=%s where id=%s'% (105.20) 'update user set id=? Where id=?', [('21pc (id varchar) 11'), ((' 20pc)]]''db=LiteDb () db.openDb (' user.db') def close (): db.closeDb () def createTables (): result=db.createTables ('create table if not exists user (id varchar)') def executeSQL ():''add, delete, check and modify' 'result= db.executeSql (' insert into user (id) values (?)', ('99') ) result = db.executeSql ('select * from user') executeSQL () close () Python parameter passing method
There are five kinds of parameters passed by Python (position parameter, default parameter, variable length parameter, keyword parameter, named keyword parameter).
Position passing, that is, parameters are passed in the defined location and order, as follows:
# location transfer example: def fun1 (a, b, c): return a + b + cprint (fun1 (1,2,3))
Keyword passing, that is, it is identified by the name of the passed parameter.
# keyword pass def fun2 (a, b, c): return a + b + cprint (fun2 (1, c, b))
The default value parameter is passed, that is, a default value is set for some parameters, and if not passed, the default value is read.
# the default value is passed def fun3 (a, bread2, canti3): return a + b + cprint (fun3 (axi1))
Tuple passing, when defining a function, we sometimes don't know how many parameters will be passed when it is called. It is useful to pass parameters in tuples. As follows:
Def fun4 (* name): print (type (name)) print (name) fun4 ((1,2,3))
Dictionary delivery, although multiple parameters can be passed through tuples, the dictionary is more convenient if you need to obtain the parameter content through key values, as shown below:
Def fun5 (a, b, * * kwargs): print (type (kwargs)) # print (a, b, kwargs) fun5 (2,3, name='Alan.hsiang', age=23) "how to use Python to implement the encapsulation of adding, deleting, changing and querying sqlite3" ends here. Thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.