Installing Pymysql
: Https://pypi.python.org/pypi/PyMySQL
1. package MySQL database into class, database and table are built first
Import Pymysql.cursors#======== Setting linked test databases ===========Host ='192.168.17.123'User='Root'Password='123456'DB='polls'#======== MYSQL Base Operating ===================classmysqloperating ():def __init__(self):Try: #Connect to the databaseSelf.connection = Pymysql.connect (host =Host, User=User, Password=Password, DB=db, CharSet='UTF8MB4', Cursorclass=pymysql.cursors.DictCursor)exceptPymysql.err.OperationalError as E:Print("Mysql Error%d:%s"% (E.args[0], e.args[1])) #Clear Table Data defClear (Self, table_name): Real_sql="Delete from"+ table_name +";"With Self.connection.cursor () as Cursor:cursor.execute ("SET foreign_key_checks = 0;") Cursor.execute (real_sql) Self.connection.commit ()
defInsert (self, TABLE_NAME, data): forKeyinchData:data[key]="'"+ str (Data[key]) +"'"Key=','. Join (Data.keys ()) value=','. Join (Data.values ()) Real_sql="INSERT into"+ table_name +" ("+ key +") VALUES ("+ Value +")"With Self.connection.cursor () as Cursor:cursor.execute (Real_sql) Self.connection.commit () #Close Database defClose (self): Self.connection.close ()if __name__=='__main__': DB=mysqloperating () table_name="poll_question"Data= {'ID': 1,'Question_text':'You buy Pro6?'} db.clear (table_name) DB.INSERT (table_name, data) Db.close ()
2. Inserting data
ImportSYSImportmysqloperating#inster table Datasdefinsert_data (table, datas): DB=mysqloperating () db.clear (table) forDatainchDatas:db.insert (table, data) Db.close ()#Create DataTable_poll_question ="polls_question"datas_poll_question=[ {'ID': 1,'Question_text':'You buy Pro6?','pub_date':'2016-07-23 09:58:56.000000'}]table_poll_choice="Polls_choice"Datas_poll_choice=[{'ID': 1,'Choice_text':'buy','votes': 0,'question_id': 1}, {'ID': 2,'Choice_text':'Not buy','votes': 0,'question_id': 1},]#init datadefinit_data (): Insert_data (Table_poll_question, datas_poll_question) insert_data (Table_poll_choice, Datas_poll_c Hoice)if __name__=='__main__': Init_data ()
3. Updating data
Python3 working with MySQL database