Python 串連資料庫

來源:互聯網
上載者:User

標籤:res   mysq   def   database   fetchall   encoding   close   resultset   comm   

python2
  • 使用MySQLdb即可
  • 代碼如下

    class sql(object):    def __init__(self):        try:            self.conn = MySQLdb.connect(                host=DB_IP,                user=DB_USER,                passwd=DB_PASSWORD,                db=DB_NAME,            )            self.conn.set_character_set(‘utf8‘)            self.cur = self.conn.cursor()            self.cur.execute(‘SET NAMES utf8;‘)            self.cur.execute(‘SET CHARACTER SET utf8;‘)            self.cur.execute(‘SET character_set_connection=utf8;‘)        except Exception as e:            raise e    # 返回二維元組,每一條記錄作為一個元組,所有的記錄再組成一個元組    def executeQuery(self, sqlcode):        try:            self.cur.execute(sqlcode)            resultSet = self.cur.fetchall()            self.conn.commit()            return resultSet        except Exception as e:            self.conn.rollback()            raise e    def executeUpdate(self, sqlCode):        try:            self.cur.execute(sqlCode)            self.conn.commit()        except Exception as e:            self.conn.rollback()            raise e    def __del__(self):        self.conn.close()
    python3
  • 使用pymysql

    db=pymysql.connect(host="192.168.1.102",user="root",password="123456",database="fwwb",charset=‘utf8‘)cursor = db.cursor()
    當參數比較多時要指定參數名,不然會報錯
  • 當查詢結果中含有中文時要指定charset參數,不然會出現亂碼
  • 將結果寫入文檔時open函數要添加encoding參數指定編碼
  • 查詢

    results = cursor.fetchall() #返回所有結果data = cursor.fetchone() #返回單條資料

Python 串連資料庫

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.