分享

Python连接SQL Server数据库 增删改查

 hdzgx 2019-12-28

Pymssql使用

麻烦的是,经常安装失败。需要先下载包,再在本地进行安装。

pip install pymssql

传送门:https://www.lfd./~gohlke/pythonlibs/#pymssql

可根据自己Python的版本来下载,之前安装Python3.7使用有些问题

安装pymssql:

 

pymssql对数据库的一些操作:

  1. import pymssql
  2. # server 数据库服务器名称或IP
  3. # user 用户名
  4. # password 密码
  5. # database 数据库名称
  6. server = "*******"
  7. user = "sa"
  8. password = "*******"
  9. database = "Python"
  10. conn = pymssql.connect(server, user, password, database)
  11. cursor = conn.cursor()
  12. # 新建表
  13. def CreateTable():
  14. sql = """
  15. IF OBJECT_ID('persons', 'U') IS NOT NULL DROP TABLE persons
  16. CREATE TABLE persons (id INT NOT NULL identity(1,1),name VARCHAR(100),age int,PRIMARY KEY(id))
  17. """
  18. cursor.execute(sql)
  19. conn.commit()
  20. # 批量插入数据
  21. def InsertData():
  22. sql = "INSERT INTO persons(name,age) VALUES (%s, %d)"
  23. data = [
  24. ('zhangsan', 15),
  25. ('lisi', 16),
  26. ('wangwu T.', 17)]
  27. cursor.executemany(sql, data)
  28. # 如果没有指定autocommit属性为True的话就需要调用commit()方法
  29. conn.commit()
  30. # 删除操作
  31. def DeleteData():
  32. sql = "delete persons where id=5"
  33. cursor.execute(sql)
  34. conn.commit()
  35. # 查询操作
  36. def SelectTable():
  37. sql = "SELECT * FROM persons"
  38. cursor.execute(sql)
  39. row = cursor.fetchone()
  40. while row:
  41. print("ID=%d, Name=%s" % (row[0], row[1]))
  42. row = cursor.fetchone()
  43. # 也可以使用for循环来迭代查询结果
  44. # for row in cursor:
  45. # print("ID=%d, Name=%s" % (row[0], row[1]))
  46. # 修改操作
  47. def UpdateData():
  48. sql = "update [persons] set name ='Python1' where id<3"
  49. cursor.execute(sql)
  50. conn.commit()
  51. def main():
  52. # CreateTable()
  53. InsertData()
  54. DeleteData()
  55. UpdateData()
  56. SelectTable()
  57. conn.close()
  58. if __name__ == '__main__':
  59. main()
  60. # 关闭连接

  mssql_helper:

  1. import pymssql
  2. class MSSQL:
  3. def __init__(self,host,user,pwd,db): #类的构造函数,初始化数据库连接ip或者域名,以及用户名,密码,要连接的数据库名称
  4. self.host=host
  5. self.user=user
  6. self.pwd=pwd
  7. self.db=db
  8. def __GetConnect(self): #得到数据库连接信息函数, 返回: conn.cursor()
  9. self.conn=pymssql.connect(host=self.host,user=self.user,password=self.pwd,database=self.db,charset='utf8')
  10. cur=self.conn.cursor() #将数据库连接信息,赋值给cur。
  11. if not cur:
  12. return(NameError,"连接数据库失败")
  13. else:
  14. return cur
  15. #执行查询语句,返回的是一个包含tuple的list,list的元素是记录行,tuple的元素是每行记录的字段
  16. def ExecQuery(self,sql): #执行Sql语句函数,返回结果
  17. cur = self.__GetConnect() #获得数据库连接信息
  18. cur.execute(sql) #执行Sql语句
  19. resList = cur.fetchall() #获得所有的查询结果
  20. #查询完毕后必须关闭连接
  21. self.conn.close() #返回查询结果
  22. return resList
  23. def ExecNonQuery(self,sql):
  24. cur = self.__GetConnect()
  25. cur.execute(sql)
  26. self.conn.commit()
  27. self.conn.close()

使用:

  1. import mssql_helper
  2. server = "********"
  3. user = "sa"
  4. password = "*********"
  5. database = "Python"
  6. mssql =""
  7. def main():
  8. global mssql
  9. mssql = mssql_helper.MSSQL(server,user,password,database)
  10. def test():
  11. rows = mssql.ExecQuery("SELECT * FROM persons")
  12. print(rows)
  13. if __name__ == '__main__':
  14. main()
  15. test()

 

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约