Advertisement
Guest User

Untitled

a guest
Oct 14th, 2017
73
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.75 KB | None | 0 0
  1. import pyodbc
  2.  
  3. driver = '{SQL Server Native Client 11.0}'
  4. host = ''
  5. database = ''
  6. user = ''
  7. password = ''
  8.  
  9. conn = pyodbc.connect(driver=driver, host=host, database=database,
  10. user=user, password=password)
  11.  
  12. cursor = conn.cursor()
  13.  
  14. # Setup - Create table
  15. cursor.execute("IF OBJECT_ID('testTable') IS NOT NULL DROP TABLE testTable")
  16. cursor.execute("CREATE TABLE testTable (col1 INT, col2 INT)")
  17. cursor.commit()
  18.  
  19. # Setup - Create procedures
  20. cursor.execute("IF OBJECT_ID('usp_insert_and_select') IS NOT NULL DROP PROCEDURE usp_insert_and_select")
  21. cursor.execute(r"""
  22. CREATE PROCEDURE usp_insert_and_select
  23. AS
  24. INSERT INTO testTable (col1, col2)
  25. VALUES (1, 2)
  26. SELECT '1', '2'
  27. """
  28. )
  29.  
  30. cursor.execute("IF OBJECT_ID('usp_just_select') IS NOT NULL DROP PROCEDURE usp_just_select")
  31. cursor.execute(r"""
  32. CREATE PROCEDURE usp_just_select
  33. AS
  34. SELECT '1', '2'
  35. """
  36. )
  37.  
  38. # Run the tests
  39. print("Execute a stored procedure and fetch the restult")
  40. print(" This will work because the sp does not insert anything")
  41. cursor.execute("usp_just_select")
  42. print(cursor.fetchall())
  43.  
  44. print()
  45. print()
  46.  
  47. try:
  48. print("Execute the stored procedure and fetch the restult")
  49. print(" This will not work because the sp inserts something")
  50. cursor.execute("usp_insert_and_select")
  51. print(cursor.fetchall())
  52.  
  53. except pyodbc.ProgrammingError:
  54. print()
  55. print("We raised pyodbc.ProgrammingError!")
  56.  
  57. finally:
  58. # Cleanup
  59. cursor.execute("IF OBJECT_ID('usp_just_select') IS NOT NULL DROP PROCEDURE usp_just_select")
  60. cursor.execute("IF OBJECT_ID('usp_insert_and_select') IS NOT NULL DROP PROCEDURE usp_insert_and_select")
  61. cursor.execute("IF OBJECT_ID('testTable') IS NOT NULL DROP TABLE testTable")
  62. cursor.close()
  63. conn.close()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement