Python连接SQL Server数据库 - pymssql使用基础

  • 时间:2023.03.22 09:09
  • 来源:Unknown
  • 编辑:谋网北海
  • 阅读次数:648

连接数据库

pymssql连接数据库的方式和使用sqlite的方式基本相同:

使用connect创建连接对象

connect.cursor创建游标对象,SQL语句的执行基本都在游标上进行

cursor.executeXXX方法执行SQL语句,cursor.fetchXXX获取查询结果等

调用close方法关闭游标cursor和数据库连接


  1. import pymssql 
  2. # server    数据库服务器名称或IP 
  3. # user      用户名 
  4. # password  密码 
  5. # database  数据库名称 
  6. conn = pymssql.connect(server, user, password, database) 
  7. cursor = conn.cursor() 
  8. # 新建、插入操作 
  9. cursor.execute(""" 
  10. IF OBJECT_ID('persons', 'U') IS NOT NULL 
  11.     DROP TABLE persons 
  12. CREATE TABLE persons ( 
  13.     id INT NOT NULL, 
  14.     name VARCHAR(100), 
  15.     salesrep VARCHAR(100), 
  16.     PRIMARY KEY(id) 
  17. ) 
  18. """
  19. cursor.executemany( 
  20.     "INSERT INTO persons VALUES (%d, %s, %s)"
  21.     [(1'John Smith''John Doe'), 
  22.      (2'Jane Doe''Joe Dog'), 
  23.      (3'Mike T.''Sarah H.')]) 
  24. # 如果没有指定autocommit属性为True的话就需要调用commit()方法 
  25. conn.commit() 
  26. # 查询操作 
  27. cursor.execute('SELECT * FROM persons WHERE salesrep=%s''John Doe'
  28. row = cursor.fetchone() 
  29. while row: 
  30.     print("ID=%d, Name=%s" % (row[0], row[1])) 
  31.     row = cursor.fetchone() 
  32. # 也可以使用for循环来迭代查询结果 
  33. # for row in cursor: 
  34. #     print("ID=%d, Name=%s" % (row[0], row[1])) 
  35. # 关闭连接 
  36. conn.close() 
 注意: 例子中查询操作的参数使用的%s而不是'%s',若参数值是字符串,在执行语句时会自动添加单引号

游标使用注意事项

一个连接一次只能有一个游标的查询处于活跃状态,如下:

  1. c1 = conn.cursor() 
  2. c1.execute('SELECT * FROM persons'
  3. c2 = conn.cursor() 
  4. c2.execute('SELECT * FROM persons WHERE salesrep=%s''John Doe'
  5. print"all persons" ) 
  6. print( c1.fetchall() )  # 显示出的是c2游标查询出来的结果 
  7. print"John Doe" ) 
  8. print( c2.fetchall() )  # 不会有任何结果 
为了避免上述的问题可以使用以下两种方式:
创建多个连接来保证多个查询可以并行执行在不同连接的游标上
使用fetchall方法获取到游标查询结果之后再执行下一个查询, 如下:
  1. c1.execute('SELECT ...'
  2. c1_list = c1.fetchall() 
  3. c2.execute('SELECT ...'
  4. c2_list = c2.fetchall() 
 游标返回行为字典变量:
上述例子中游标获取的查询结果的每一行为元组类型,
可以通过在创建游标时指定as_dict参数来使游标返回字典变量,
字典中的键为数据表的列名
  1. conn = pymssql.connect(server, user, password, database) 
  2. cursor = conn.cursor(as_dict=True
  3. cursor.execute('SELECT * FROM persons WHERE salesrep=%s''John Doe'
  4. for row in cursor: 
  5.     print("ID=%d, Name=%s" % (row['id'], row['name'])) 
  6. conn.close() 
 
使用with语句(上下文管理器):
可以通过使用with语句来省去显示的调用close方法关闭连接和游标
  1. with pymssql.connect(server, user, password, database) as conn: 
  2.     with conn.cursor(as_dict=True) as cursor: 
  3.         cursor.execute('SELECT * FROM persons WHERE salesrep=%s''John Doe'
  4.         for row in cursor: 
  5.             print("ID=%d, Name=%s" % (row['id'], row['name'])) 
 
调用存储过程
pymssql 2.0.0以上的版本可以通过cursor.callproc方法来调用存储过程
  1. with pymssql.connect(server, user, password, database) as conn: 
  2.     with conn.cursor(as_dict=True) as cursor: 
  3.         # 创建存储过程 
  4.         cursor.execute(""" 
  5.         CREATE PROCEDURE FindPerson 
  6.             @name VARCHAR(100) 
  7.         AS BEGIN 
  8.             SELECT * FROM persons WHERE name = @name 
  9.         END 
  10.         """
  11.         # 调用存储过程 
  12.         cursor.callproc('FindPerson', ('Jane Doe',)) 
  13.         for row in cursor: 
  14.             print("ID=%d, Name=%s" % (row['id'], row['name'])) 
 


本站部分文章均来自互联网,具体由文章来源标注,如有侵犯您的权益请联系删除,谢谢!