Python下使用MySQLdb模組

來源:互聯網
上載者:User

1、匯入模組
import MySQLdb>>> help ('MySQLdb')
>>> help ('MySQLdb.cursors')
2、串連資料庫
conn =   MySQLdb.Connection(host='host',user= 'user',passwd= 'password',db = 'dbname',port=port)

例如:

conn = connect(host='10.0.*.*',user='root',db='mysql',port=3306,passwd='test')

含義是:
host:需要串連Mysql的主機ip
user:串連mysql使用的使用者名稱
password:串連使用的使用者名稱密碼
dbname:預設開啟的資料庫
串連成功後,如需切換該使用者的其他資料庫,使用以下語句:
conn.select_db('database name') 3、擷取資料庫操作遊標(指標)
因該模組底層其實是調用C API的,所以,需要先得到當前指向資料庫的指標
cur =   conn.cursor() 4、對資料庫的相關操作
先使用指標對象執行SQL查詢語句:
cur.execute('select * from tables')
其傳回值為SQL語句得到的行數,如:2L,表示2行。
然後,可以從該對象的fetchone或fetchall方法得到行資訊。
指標對象的fetchone()方法,是每次得到一行的tuple傳回值:
  1. >>> result=cur.fetchone()  
  2. >>> print result  
指標對象的fetchall()方法,是得到一組tuple,其內容為由行資訊組成的tuple值:
  1. >>> cur.scroll(0,'absolute')  
  2. >>> result=cur.fetchall()  
  3. >>> print result  
  • 1
  • 2
  • 下一頁

相關文章

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.