Guest User

Untitled

a guest
Aug 17th, 2018
74
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.12 KB | None | 0 0
  1. import mysql.connector
  2. from mysql.connector import errorcode
  3.  
  4. import time
  5. import sys
  6.  
  7. conn=None
  8.  
  9. def add_employee(conn, emp_no, first_name, last_name):
  10. try:
  11. cur = conn.cursor()
  12. cur.execute(
  13. "INSERT INTO employees VALUES (%s, %s, %s)",
  14. (emp_no, first_name, last_name)
  15. )
  16. except mysql.connector.Error:
  17. print "Database connection error, trying to reconnect ..."
  18. connect()
  19.  
  20. def find_employee(conn, emp_no):
  21. try:
  22. cur = conn.cursor()
  23. cur.execute(
  24. "SELECT concat('Hostname:',@@hostname),concat(': ',@@port,' ; '), first_name, last_name FROM employees "
  25. "WHERE emp_no = %s", (emp_no, )
  26. )
  27. for row in cur:
  28. print row[0],row[1],row[2],row[3]
  29. except mysql.connector.Error:
  30. print "Database connection error, trying to reconnect ..."
  31. connect()
  32.  
  33. def connect():
  34. global conn
  35. print "inside connect()"
  36. try:
  37. conn=mysql.connector.connect(user="idcAdmin", password="idcAdmin", database="test", port=sys.argv[1], host="127.0.0.1",
  38. autocommit=True)
  39.  
  40. except mysql.connector.Error as err:
  41. if err.errno == errorcode.ER_ACCESS_DENIED_ERROR:
  42. print("Something is wrong with your user name or password")
  43. sys.exit()
  44. elif err.errno == errorcode.ER_BAD_DB_ERROR:
  45. print("Database does not exist")
  46. sys.exit()
  47. else:
  48. print(err)
  49.  
  50. print "Error trying to get a new database connection"
  51. time.sleep(1)
  52. return conn
  53.  
  54. if len(sys.argv) != 2:
  55. print "Syntax: ", sys.argv[0], "<port> exiting ...."
  56. sys.exit()
  57.  
  58. print "Starting to insert data into MySQL on port:", sys.argv[1]
  59.  
  60. connect()
  61. cur = conn.cursor()
  62. cur.execute("DROP TABLE IF EXISTS employees")
  63. cur.execute(
  64. "CREATE TABLE employees ("
  65. " emp_no INT PRIMARY KEY, "
  66. " first_name CHAR(40), "
  67. " last_name CHAR(40)"
  68. ")"
  69. )
  70.  
  71. high=10
  72. for x in range(0, high):
  73. add_employee(conn, x, "John"+":"+str(x), "Doe")
  74.  
  75. high+=1
  76. while True:
  77. add_employee(conn, high, "John"+":"+str(high), "Doe")
  78. time.sleep(0.5)
  79. for x in range(high-5, high):
  80. find_employee(conn, x)
  81. high+=1
Add Comment
Please, Sign In to add comment