python3.6串連mysql

來源:互聯網
上載者:User

標籤:擷取   fetch   ip命令   一個資料庫   str   需要   csdn   資料庫   with   

初次學習python,因為python串連mysql的時候,需要安裝mysql驅動模組

之前按照廖雪峰網站上的方法安裝mysql驅動的方法:

 

MySQL官方提供了mysql-connector-python驅動,但是安裝的時候需要給pip命令加上參數--allow-external:

$ pip install mysql-connector-python --allow-external mysql-connector-python

如果上面的命令安裝失敗,可以試試另一個驅動:

$ pip install mysql-connector


這兩種方法都嘗試了,都沒有成功

後來發現,因為使用的是python3.6,好像上面的兩種方法都是提供給之前的python版本,然而python3.6卻怎麼都裝不上,一直報一個設定檔有問題

之後在http://blog.csdn.net/wochunyang/article/details/52457969找到瞭解決的辦法


通過pip 安裝pymysql:
pip install pymysql

串連資料庫程式碼範例:

#coding=utf-8
#匯入pymysql的包
import pymysql import pymysql.cursors
#擷取一個資料庫連接,注意如果是UTF-8類型的,需要制定資料庫
#port 必須是數字不能為字串
connection=pymysql.connect(host=‘localhost‘, user=‘root‘, password=‘123456‘, db=‘test‘, port=3307, charset=‘utf8‘)
try:
  #擷取一個遊標
  with connection.cursor() as cursor:
    sql=‘select * from user‘ cout=cursor.execute(sql)
    print("數量: "+str(cout))
      for row in cursor.fetchall():
        #print(‘%s\t%s\t%s‘ %row)
        #注意int類型需要使用str函數轉義
        print("ID: "+str(row[0])+‘ 名字: ‘+row[1]+" 性別: "+row[2])
      connection.commit()
finally:
  connection.close()


python3.6串連mysql

聯繫我們

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