1 #!/usr/bin/env python 2 #coding=utf-8 3 from __future__ import with_statement 4 from contextlib import closing 5 import inspect 6 import pymssql 7 import uuid 8 import datetime 9 10 #查詢操作11 with closing(pymssql.connect(host='localhost',user='sa',password='ssss',database='blogs')) as conn :12 cur = conn.cursor()13 #SELECT 長串連查詢操作(逐條方式擷取資料),這個我不能肯定,還請各位看官確認一下,有空我在具體測試一下。14 sql = "select * from pcontent"15 cur.execute(sql)16 for i in range(cur.rowcount):17 print cur.fetchone()18 #SELECT 短連結查詢操作(一次查詢將所有資料取出)19 sql = "select * from pcontent"20 cur.execute(sql)21 print cur.fetchall()22 #INSERT 23 sql = "INSERT INTO pcontent(title)VAlUES(%s)"24 uuidstr = str(uuid.uuid1())25 cur.execute(sql,(uuidstr,))26 conn.commit()27 print cur._result28 #INSERT 擷取IDENTITY(在插入一個值,希望獲得主鍵的時候經常用到,很不優雅的方式)29 sql = "INSERT INTO pcontent(title)VAlUES(%s);SELECT @@IDENTITY"30 uuidstr = str(uuid.uuid1())31 cur.execute(sql,(uuidstr,))32 print "arraysite:",cur.arraysize33 print cur._result[1][2][0][0]#不知道具體的做法,目前暫時這樣使用34 conn.commit()35 #Update36 sql = 'update pcontent set title = %s where id=1'37 cur.execute(sql,(str(datetime.datetime.today()),))38 conn.commit()39 #參數化查詢這個是為了避免SQL攻擊的40 sql = "select * from pcontent where id=%d"41 cur.execute(sql,(1,))42 print cur.fetchall()43 44 # 調用預存程序SP_GetALLContent 無參數45 sql = "Exec SP_GetALLContent"46 cur.execute(sql)47 print cur.fetchall()48 # 調用預存程序SP_GetContentByID 有參數的49 sql = "Exec SP_GetContentByID %d"50 cur.execute(sql,(3,))51 print cur.fetchall()52 #調用預存程序SP_AddContent 有output參數的(很不優雅的方式)53 sql = "DECLARE @ID INT;EXEC SP_AddContent 'ddddd',@ID OUTPUT;SELECT @ID"54 cur.execute(sql)55 print cur._result