python訪問mysql初試--菜鳥筆記

來源:互聯網
上載者:User

標籤:val   --   exception   語句   mysql資料庫   預存程序   col   elf   key   

【基本思路】

通過本地python指令碼,訪問遠程mysql資料庫,並做DDL和DML操作

 1 #-*-encoding:UTF-8-*- 2 """ 3 測試Python至MySQL的串連及操作 4 """ 5  6 import MySQLdb 7  8 connstr="""host=‘134.64.14.48‘,port=3306,user=‘root‘,passwd=‘*******‘,db=‘test‘""" 9 #連接字串10 11 conn=MySQLdb.connect(connstr)12 #建立連結13 mycursor=conn.cursor()14 #擷取遊標,用遊標操作資料庫15 16 #建立表17 ctable="""CREATE TABLE test (name VARCHAR(20),id INT(10) primary key)"""18 mycursor.execute(ctable)19 20 #插入資料21 rec1="""INSERT INTO test values(‘a1‘,11)"""22 rec2="""INSERT INTO test values(‘a2‘,22)"""23 rec3="""INSERT INTO test values(‘a3‘,33)"""24 recs=[]25 recs.append(rec1)26 recs.append(rec2)27 recs.append(rec3)28 for insert in recs:29      try:30             mycursor.execute(insert)31             conn.commit()32      except Exception,e:33             print e34             conn.rollback()35             36 conn.close()  #關閉連結

mycursor用來執行命令的方法: 
callproc(self, procname, args):用來執行預存程序,接收的參數為預存程序名和參數列表,傳回值為受影響的行數 
execute(self, query, args):執行單條sql語句,接收的參數為sql語句本身和使用的參數列表,傳回值為受影響的行數 
executemany(self, query, args):執行單條sql語句,但是重複執行參數列表裡的參數,傳回值為受影響的行數 
nextset(self):移動到下一個結果集 

python訪問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.