Testing pymysql and SQLAlchemy connections to mysql

Submitted by code_admin on Fri, 04/05/2019 - 10:08

I setup a test amazon mariadb database to test how connections can occur using ssl

  1. '''
  2.  
  3.  
  4. ##connect to server
  5. #mysql -uroot -hXXX.eu-west-2.rds.amazonaws.com --ssl-ca ./rds-combined-ca-bundle.pem -p
  6.  
  7. (Passwords hard coded as the test database should be deleted after it is done)
  8.  
  9. create database tmp_test_db CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci;
  10. ## Check it is utf-8
  11. use mysql;
  12. SELECT schema_name, default_character_set_name FROM information_schema.SCHEMATA;
  13. CREATE USER ssl_user IDENTIFIED BY 'dsghyGFtuFG65G6t4rewsds';
  14. grant ALL on tmp_test_db.* TO ssl_user@'%' REQUIRE SSL;
  15. CREATE USER user IDENTIFIED BY 'DSF435354fhgGTH5T';
  16. grant ALL on tmp_test_db.* TO user@'%';
  17. FLUSH PRIVILEGES;
  18. select host, user, ssl_type from user;
  19.  
  20. SSL Test
  21. #mysql -ussl_user -hXXX.eu-west-2.rds.amazonaws.com -p"dsghyGFtuFG65G6t4rewsds" --ssl-ca ./rds-combined-ca-bundle.pem
  22.  
  23. No SSL Test
  24. #mysql -uuser -hXXX.eu-west-2.rds.amazonaws.com -p"DSF435354fhgGTH5T"
  25. '''
  26.  
  27. print("Start of test of DB connections")
  28.  
  29. import pymysql
  30.  
  31. user="user"
  32. passwd="DSF435354fhgGTH5T"
  33. ssluser="ssl_user"
  34. sslpasswd="dsghyGFtuFG65G6t4rewsds"
  35.  
  36. host="XXX.eu-west-2.rds.amazonaws.com"
  37. db="tmp_test_db"
  38.  
  39.  
  40. def testDB_Using_pymysql_directly(user, passwd, host, db):
  41.   ssl = {'ca': '/home/robert/dbtestTmp/rds-combined-ca-bundle.pem'}
  42.   query = "select * from tasks;"
  43.   db = pymysql.connect(host=host,user=user,passwd=passwd,db=db, ssl=ssl)
  44.   cur = db.cursor()
  45.   cur.execute(query)
  46.   db.commit()
  47.   result = cur.fetchall()
  48.   print(result)
  49.   db.close()
  50.  
  51. print("pymysql Testing non-SSL")
  52. testDB_Using_pymysql_directly(user, passwd, host, db)
  53. print("pymysql Testing SSL")
  54. testDB_Using_pymysql_directly(ssluser, sslpasswd, host, db)
  55.  
  56. from sqlalchemy import create_engine
  57.  
  58. def testDB_Using_SQLAlchemy_and_pymysql(user, passwd, host, db):
  59.   connectionString = "mysql+pymysql://" + user + ":" + passwd + "@" + host + "/" + db
  60.   connect_args = {
  61.     "ssl": {'ca': '/home/robert/dbtestTmp/rds-combined-ca-bundle.pem'}
  62.   }
  63.   engine = create_engine(connectionString, pool_recycle=3600, pool_size=40, max_overflow=0, connect_args=connect_args)
  64.   connection = engine.connect()
  65.  
  66. print("SQLAlchemy Testing non-SSL")
  67. testDB_Using_SQLAlchemy_and_pymysql(user, passwd, host, db)
  68. print("SQLAlchemy Testing SSL")
  69. testDB_Using_SQLAlchemy_and_pymysql(ssluser, sslpasswd, host, db)
  70.  
  71.  
  72. print("End of test")

Tags

RJM Article Type
Work Notes