This article mainly introduces the simple encapsulation of adding, deleting, modifying, and querying PythonSql databases, interested friends can refer to the examples in this article to share with you how to use Python to add, delete, modify, and query databases for simple encapsulation. the specific content is as follows:
1. insert
Import mysql. connectorimport osimport codecs # Set database user name and password user = 'root'; # user name pwd = 'root'; # Password host = 'localhost'; # IP address db = 'mysql '; # Name of the database to be operated charset = 'utf-8' cnx = mysql. connector. connect (user = user, password = pwd, host = host, database = db) # set cursor = cnx. cursor (dictionary = True) # insert data # print (insert ('gelixi _ help_type ', {'type _ name':' \ 'sddfdsfs \'', 'type _ sort ': '000000'}) def insert (table_name, insert_dict): param = ''; value =''; if (isinstance (insert_dict, dict )): for key in insert_dict.keys (): param = param + key + "," value = value + insert_dict [key] + ', 'param = param [: -1] value = value [:-1] SQL = "insert into % s (% s) values (% s)" % (table_name, param, value) cursor.exe cute (SQL) id = cursor. lastrowid cnx. commit () return id
2. delete
def delete(table_name,where=''): if(where!=''): str='where' for key_value in where.keys(): value=where[key_value] str=str+' '+key_value+'='+value+' '+'and' where=str[:-3] sql="delete from %s %s"%(table_name,where) cursor.execute(sql) cnx.commit()
3. select
# Obtain database information # print (select ({'table': 'gelixi _ help_type ', 'where': {'Help _ show': '1 '}}, 'type _ name, type_id ') def select (param, fields =' * '): table = param ['table'] if ('where' in param ): thewhere = param ['where'] if (isinstance (thewhere, dict): keys = thewhere. keys () str = 'where'; for key_value in keys: value = thewhere [key_value] str = str + ''+ key_value + '=' + value +'' + 'and' where = str [:-3] else: where = ''SQL =" select % s from % s "% (fields, table, where) cursor.exe cute (SQL) result = cursor. fetchall () return result
4. showtable, showcolumns
# Show table creation statement # table string table name # return string table creation statement def showCreateTable (table): SQL = 'show create table % s' % (table) cursor.exe cute (SQL) result = cursor. fetchall () [0] return result ['create Table'] # print (showCreateTable ('gelixi _ admin') # display the Table structure statement def showColumns (table ): SQL = 'show columns from % s' % (table) print (SQL) cursor.exe cute (SQL) result = cursor. fetchall () dict1 ={} for info in result: dict1 [info ['field'] = info return dict1
The above operations are related to the addition, deletion, modification, and query operations of the Python SQL database. I hope this will be helpful for your learning.
For more articles about simple encapsulation methods for adding, deleting, modifying, and Querying SQL databases in Python, refer to PHP Chinese network!