Recently, I learned Python, recorded the code and experience of writing to learn Python, wrote a query statement using Python MySQL and made a db_config.py configuration information.
1. db_config.py configuration file
1 #/usr/bin/python2 3 classmysql_config ():4 " "def __init__ (self,name):5 #print ' aaaa '6 self.name = name7 Print name8 " "9 defGet_config (self,name):TenSelf.name =name OneConfig ={ A 'TestDB':{ - 'Host':'192.168.6.6', - 'User':'PhP2', the 'passwd':'123456', - 'DB':'TestDB', - 'Port': 3307, - }, + } - returnConfig[name]
2, their own package of MySQL connection class Db_mysql first practice practiced hand.
1 #/uer/bin/python 2 3 ImportMySQLdb;4 fromDb_configImportMysql_config5M_config =Mysql_config ()6 classdb_mysql ():7 def __init__(self):8 Print 'class:db_mysql-import-true'9 Ten defConnect (self,name): One #self.sql = SQL ASelf.name =name - Try: - #self.config = M_CONFIG.ABC (name) theConfig =m_config.get_config (name) -db = MySQLdb.connect (* *config) -cursor =db.cursor () - #cursor.execute (SQL) + exceptMySQLdb.connector.Error as err: - Print("Something went wrong: {}". Format (err)) + returncursor A at defExecute (self,cursor,sql): - cursor.execute (SQL) - returncursor - - defFetchall (self,cursor): -data =Cursor.fetchall () in returnData - to defFetchone (self,cursor): + returnCursor.fetchone ()
3, test whether to obtain data ....
1 #/usr/bin/python/ 2 3 fromMysqlImportDb_mysql4Mysql_obj =Db_mysql ()5 6sql ="SELECT * from Test WHERE ' p_id ' = ' + ' LIMIT";7Cursor_connect = Mysql_obj.connect ('TestDB')8Cursor_execute =Mysql_obj.execute (cursor_connect,sql)9data =Mysql_obj.fetchall (Cursor_execute)Ten One PrintData
Python Learning-mysql connection and Db_config configuration