python--操作資料庫

來源:互聯網
上載者:User

標籤:資料   .com   l資料庫   關閉   int   style   print   擷取   date   

python操作mysql資料庫 python3中操作mysql資料需要安裝一個第三方模組,pymysql,使用pip install pymysql安裝即可,在python2中是MySQLdb模組,在python3中沒有MySQLdb模組了,所以使用pymysql。

一、操作資料
操作資料庫分為以下幾個步驟

1.連上資料庫 帳號 密碼 ip 連接埠號碼 資料庫
2.建立遊標
3.執行sql
4.擷取結果
5.關閉遊標
6.連結關閉

 1 sql_connect = pymysql.connect( 2     host=‘118.24.3.40‘,user=‘jxz‘,passwd=‘123456‘, 3     port=3306,db=‘jxz‘,charset=‘utf8‘ 4     #port必須寫int類型 5     #charset這裡必須寫utf8 6 ) 7 cur = sql_connect.cursor()#建立遊標 8 cur.execute(‘select * from stu;‘)#執行sql 9 res = cur.fetchall()#擷取所有返回結果10 11 # cur.execute(‘insert into stu VALUE (6,"ytt","女");‘)12 # delete update insert 語句都需要commit一下13 # sql_connect.commit()14 15 print(res)16 cur.close()#關閉遊標17 sql_connect.close()#關閉連結

將操作資料庫寫一個函數

 1 def my_db(host,user,passwd,db,sql,port=3306,charset=‘utf8‘): 2     import  pymysql 3     coon = pymysql.connect(user=user, 4                            host=host, 5                            port=port, 6                            passwd=passwd, 7                            db=db, 8                            charset=charset 9                            )10     cur = coon.cursor()#建立遊標11     cur.execute(sql)#執行sql12     if sql.strip()[:6].upper()==‘SELECT‘:13         res = cur.fetchall()14         print(res)15     else:16         coon.commit()17         res = ‘ok‘18     cur.close()19     coon.close()20     return res

 

 

 

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.