MSSQL.py 2.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. #coding=utf-8
  2. #!/usr/bin/env python
  3. #-------------------------------------------------------------------------------
  4. # Name: pymssqlTest.py
  5. # Purpose: 测试 pymssql库,该库到这里下载:http://www.lfd.uci.edu/~gohlke/pythonlibs/#pymssql
  6. #
  7. # Author: scott
  8. #
  9. # Created: 04/02/2012
  10. #-------------------------------------------------------------------------------
  11. import pymssql
  12. class MSSQL:
  13. """
  14. 对pymssql的简单封装
  15. pymssql库,该库到这里下载:http://www.lfd.uci.edu/~gohlke/pythonlibs/#pymssql
  16. 使用该库时,需要在Sql Server Configuration Manager里面将TCP/IP协议开启
  17. 用法:
  18. """
  19. def __init__(self,host,user,pwd,db):
  20. self.host = host
  21. self.user = user
  22. self.pwd = pwd
  23. self.db = db
  24. def __GetConnect(self):
  25. """
  26. 得到连接信息
  27. 返回: conn.cursor()
  28. """
  29. if not self.db:
  30. raise(NameError,"没有设置数据库信息")
  31. self.conn = pymssql.connect(host=self.host,user=self.user,password=self.pwd,database=self.db,charset="utf8")
  32. cur = self.conn.cursor()
  33. if not cur:
  34. raise(NameError,"连接数据库失败")
  35. else:
  36. return cur
  37. def ExecQuery(self,sql):
  38. """
  39. 执行查询语句
  40. 返回的是一个包含tuple的list,list的元素是记录行,tuple的元素是每行记录的字段
  41. 调用示例:
  42. ms = MSSQL(host="localhost",user="sa",pwd="123456",db="PythonWeiboStatistics")
  43. resList = ms.ExecQuery("SELECT id,NickName FROM WeiBoUser")
  44. for (id,NickName) in resList:
  45. print str(id),NickName
  46. """
  47. try:
  48. cur = self.__GetConnect()
  49. cur.execute(sql)
  50. resList = cur.fetchall()
  51. except Exception as e:
  52. print(e)
  53. finally:
  54. #查询完毕后必须关闭连接
  55. self.conn.close()
  56. return resList
  57. def ExecNonQuery(self,sql):
  58. """
  59. 执行非查询语句
  60. 调用示例:
  61. cur = self.__GetConnect()
  62. cur.execute(sql)
  63. self.conn.commit()
  64. self.conn.close()
  65. """
  66. cur = self.__GetConnect()
  67. cur.execute(sql)
  68. self.conn.commit()
  69. self.conn.close()
  70. def main():
  71. ## ms = MSSQL(host="localhost",user="sa",pwd="123456",db="PythonWeiboStatistics")
  72. ## #返回的是一个包含tuple的list,list的元素是记录行,tuple的元素是每行记录的字段
  73. ## ms.ExecNonQuery("insert into WeiBoUser values('2','3')")
  74. ms = MSSQL(host="192.168.1.100",user="sa",pwd="`12345",db="Con2010_zjhw")
  75. resList = ms.ExecQuery("SELECT * from comp")
  76. print(resList)
  77. #for (id,weibocontent) in resList:
  78. # print str(weibocontent).decode("utf8")
  79. if __name__ == '__main__':
  80. main()