Python mssql数据库操作

  
    
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._result 28 # 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.arraysize 33 print cur._result[ 1 ][ 2 ][0][0] # 不知道具体的做法,目前暂时这样使用 34 conn.commit() 35 # Update 36 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

你可能感兴趣的:(python)