#! / usr/ bin/ env python #- * - encoding: UTF- 8- * - "" " 測試MySQL的鏈接及操做 " "" import MySQLdb connstring= "host='localhost',port=3306,user='root',passwd='*****',db='python'" #鏈接字符串 try : conn= MySQLdb. connect( connstring) except Exception , e: print e break mycursor= conn. cursor( ) #獲取遊標,用遊標操做數據庫 #建立表 ctable= "" "CREATE TABLE test if not exists(name VARCHAR(30),uid INT(10) primary key)" "" mycursor. execute( ctable) #插入數據 insert1= "" "INSERT INTO test(name='aaa',uid=111)" "" insert2= "" "INSERT INTO test(name='bbb',uid=222)" "" insert3= "" "INSERT INTO test(name='ccc',uid=333)" "" inserts= [ ] inserts[ 0] . append( insert1) inserts[ 1] . append( insert2) inserts[ 2] . append( insert3) for insert in inserts: try : mycursor. execute( insert) except Exception , e: print e #刪除數據 #註釋掉,下邊查詢要用到數據,只記錄操做 #mycursor. execute( "" "DELETE FROM test WHERE name='aaa'" "" ) #多表刪除 #delmany= "" "" DELETE FROM table1, table2, table3 WHERE table1. uid= XXX AND table2. uid= table3. uid"" " #mycursor.execute(delmany) 繼續...... #查詢表 slct= "" "SELECT * FROM test""" mycursor.execute(slct) #查詢緩衝池中匹配記錄 records=mycursor.fetchall() for record in records: print record #結束數據庫操做,釋放遊標 mycursor.close() #提交操做 conn.commit() #關閉鏈接 conn.close() 以上是基本操做,補充幾個對象的方法和屬性: 1.connection(鏈接)對象: 方法名 做用 close() 關閉數據庫 commit() 提交當前事務 rollback() 取消當前事務 cursor() 獲取當前鏈接的遊標對象 errorhandler(cxn,cur,errcls,errval) 做爲已給遊標的句柄 2.cursor遊標對象屬性及方法: 屬性方法 描述 arraysize 使用fetchmany()方法時一次取出的記錄數,默認爲1 connection 建立此遊標的鏈接(可選) discription 返回遊標的活動狀態,包括(7元素):(name,type_code,display_size,internal_size,precision,scale,null_ok)其中name,type_code是必須的。 lastrowid 返回最後更新行的ID(可選),若是數據庫不支持,返回None rowcount 最後一次execute()返回或影響的行數 callproc(func[,args]) 調用一個存儲過程 close() 關閉遊標 execute(op[,args]) 執行sql語句或數據庫命令 executemany(op,args) 一次執行多條sql語句,執行的條數由arraysize給出 fetchone() 匹配結果的下一行 fetchall() 匹配全部剩餘結果 fetchmany(size-cursor,arraysize) 匹配結果的下幾行 __iter__() 建立迭代對象(可選,參考next()) messages 遊標執行好數據庫返回的信息列表(元組集合) next() 使用迭代對象獲得結果的下一行 nextset() 移動到下一個結果集(若是支持的話) rownumber 當前結果集中游標的索引(從0行開始) setinput-size(sizes) 設置輸入最大值 setoutput-size(sizes[,col]) 設置列輸出的緩衝值 python鏈接MySQL數據庫講解 模塊功能:connect()方法 * connect()方法用於鏈接數據庫,返回一個數據庫鏈接對象。若是要鏈接一個位於host.remote.com服務器上名爲fourm的MySQL數據庫,鏈接串能夠這樣寫: db = MySQLdb.connect(host="remote.com",user="user",passwd="xxx",db="fourm" ) connect()的參數列表以下: host,鏈接的數據庫服務器主機名,默認爲本地主機(localhost)。 user,鏈接數據庫的用戶名,默認爲當前用戶。 passwd,鏈接密碼,沒有默認值。 db,鏈接的數據庫名,沒有默認值。 conv,將文字映射到Python類型的字典。默認爲MySQLdb.converters.conversions cursorclass,cursor()使用的種類,默認值爲MySQLdb.cursors.Cursor。 compress,啓用協議壓縮功能。 named_pipe,在windows中,與一個命名管道相鏈接。 init_command,一旦鏈接創建,就爲數據庫服務器指定一條語句來運行。 read_default_file,使用指定的MySQL配置文件。 read_default_group,讀取的默認組。 unix_socket,在unix中,鏈接使用的套接字,默認使用TCP。 port,指定數據庫服務器的鏈接端口,默認是3306。 * 鏈接對象的db.close()方法可關閉數據庫鏈接,並釋放相關資源。 * 鏈接對象的db.cursor([cursorClass])方法返回一個指針對象,用於訪問和操做數據庫中的數據。 * 鏈接對象的db.begin()方法用於開始一個事務,若是數據庫的AUTOCOMMIT已經開啓就關閉它,直到事務調用commit()和rollback()結束。 *鏈接對象的db.commit()和db.rollback()方法分別表示事務提交和回退。 *指針對象的cursor.close()方法關閉指針並釋放相關資源。 *指針對象的cursor.execute(query[,parameters])方法執行數據庫查詢。 *指針對象的cursor.fetchall()可取出指針結果集中的全部行,返回的結果集一個元組(tuples)。 *指針對象的cursor.fetchmany([size=cursor.arraysize])從查詢結果集中取出多行,咱們可利用可選的參數指定取出的行數。 *指針對象的cursor.fetchone()從查詢結果集中返回下一行。 *指針對象的cursor.arraysize屬性指定由cursor.fetchmany()方法返回行的數目,影響fetchall()的性能,默認值爲1。 *指針對象的cursor.rowcount屬性指出上次查詢或更新所發生行數。-1表示還沒開始查詢或沒有查詢到數據。 模塊功能演示 #!/usr/bin/python import MySQLdb try: connection = MySQLdb.connect(user="user",passwd="password",host="xxx",db="test") except: print "Could not connect to MySQL server." exit( 0 ) try: cursor = connection.cursor() cursor.execute( "SELECT note_id,note_detail FROM note where note_id = 1" ) print "Rows selected:", cursor.rowcount for row in cursor.fetchall(): print "note : ", row[0], row[1] cursor.close()