python 连接sql server数据库-对表的基本操作

谁借莪1个温暖的怀抱¢ 2023-06-23 13:26 83阅读 0赞

连接sql server数据库,需要导入第三方库pymssql。

  1. import pymssql
  2. server = "" # 连接服务器地址
  3. user = ""
  4. password = ""
  5. conn = pymssql.connect(server, user, password, "RPAMON") #获取连接
  6. cursor = conn.cursor() # 获取光标
  7. # 创建表
  8. cursor.execute(""" IF OBJECT_ID('persons', 'U') IS NOT NULL DROP TABLE persons CREATE TABLE persons ( id INT NOT NULL, name VARCHAR(100), salesrep VARCHAR(100), PRIMARY KEY(id) ) """)
  9. # 插入多行数据
  10. cursor.executemany(
  11. "INSERT INTO persons VALUES (%d, %s, %s)",
  12. [(1, 'John Smith', 'John Doe'),
  13. (2, 'Jane Doe', 'Joe Dog'),
  14. (3, 'Mike T.', 'Sarah H.')])
  15. # 你必须调用 commit() 来保持你数据的提交如果你没有将自动提交设置为true
  16. conn.commit()
  17. # 查询数据
  18. cursor.execute('SELECT * FROM persons WHERE salesrep=%s', 'John Doe')
  19. # 遍历数据(存放到元组中) 方式1
  20. row = cursor.fetchone()
  21. while row:
  22. print("ID=%d, Name=%s" % (row[0], row[1]))
  23. row = cursor.fetchone()
  24. # 遍历数据(存放到元组中) 方式2
  25. for row in cursor:
  26. print('row = %r' % (row,))
  27. # 关闭连接
  28. conn.close()
  29. # 注:在任何时候,在一个连接下,一次正在执行的数据库操作只会出现一个cursor对象

发表评论

表情:
评论列表 (有 0 条评论,83人围观)

还没有评论,来说两句吧...

相关阅读

    相关 SQL Server连接

    在关系数据库管理系统中,表建立时各数据之间的关系不必确定,常把一个实体的所有信息存放在一个表中。当检索数据时,通过连接操作查询出存放在多个表中的不同实体的信息。连接操作给用户带