python學習之 -mysql 串連和db_config配置

來源:互聯網
上載者:User

標籤:style   blog   color   os   使用   sp   for   檔案   資料   

最近學習python,記錄下自己寫學習python的代碼和心得,自己寫了一個使用python mysql 的查詢語句和做的一個db_config.py 配置資訊。

1、db_config.py 設定檔

 1 #/usr/bin/python 2  3 class mysql_config(): 4     ‘‘‘def __init__(self,name): 5         #print ‘aaaa‘ 6         self.name = name 7         print name 8     ‘‘‘ 9     def get_config(self,name):10         self.name = name11         config ={12             ‘testdb‘:{                                                                                                            13                 ‘host‘:‘192.168.6.6‘,14                 ‘user‘:‘php2‘,15                 ‘passwd‘:‘123456‘,16                 ‘db‘:‘testdb‘,17                 ‘port‘:3307,18             },19         }20         return config[name]

2、自己封裝的mysql 串連class db_mysql  先練練手。

 1 #/uer/bin/python                                                                                                                            2  3 import MySQLdb; 4 from db_config import mysql_config 5 m_config  = mysql_config() 6 class db_mysql(): 7     def __init__(self): 8         print ‘class:db_mysql -import -true‘ 9 10     def connect(self,name):11         #self.sql  = sql12         self.name = name13         try:14             #self.config = m_config.abc(name)15             config  = m_config.get_config(name)16             db = MySQLdb.connect(**config)17             cursor = db.cursor()18             #cursor.execute(sql)19         except MySQLdb.connector.Error as err:20             print("Something went wrong: {}".format(err))21         return cursor22         23     def execute(self,cursor,sql):24         cursor.execute(sql)25         return cursor26 27     def fetchall(self,cursor):28         data = cursor.fetchall()29         return data30         31     def fetchone(self,cursor):32         return cursor.fetchone()

3、測試能否擷取到資料。。。。。。。

 1 #/usr/bin/python/                                                                                                                           2  3 from mysql import db_mysql 4 mysql_obj = db_mysql() 5  6 sql ="SELECT * FROM test WHERE `p_id` = ‘1000‘ LIMIT 10"; 7 cursor_connect  = mysql_obj.connect(‘testdb‘) 8 cursor_execute  = mysql_obj.execute(cursor_connect,sql) 9 data            = mysql_obj.fetchall(cursor_execute)10 11 print data;

 

python學習之 -mysql 串連和db_config配置

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.