Python SQL database simple encapsulation of addition, deletion, modification, and query operations, pythonsql
The examples in this article share with you how to use Python to encapsulate the addition, deletion, modification, and query of databases for your reference. 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.