2025-02-09 18:53:36 +01:00
|
|
|
import pymysql
|
|
|
|
|
|
|
|
|
2025-02-09 19:16:42 +01:00
|
|
|
def create_db(hostname="localhost", port=3306, username=None, password=None, dbname=None):
|
2025-02-09 18:53:36 +01:00
|
|
|
"""Create test database.
|
|
|
|
|
|
|
|
:param hostname: string
|
|
|
|
:param port: int
|
|
|
|
:param username: string
|
|
|
|
:param password: string
|
|
|
|
:param dbname: string
|
|
|
|
:return:
|
|
|
|
|
|
|
|
"""
|
|
|
|
cn = pymysql.connect(
|
2025-02-09 19:16:42 +01:00
|
|
|
host=hostname, port=port, user=username, password=password, charset="utf8mb4", cursorclass=pymysql.cursors.DictCursor
|
2025-02-09 18:53:36 +01:00
|
|
|
)
|
|
|
|
|
|
|
|
with cn.cursor() as cr:
|
2025-02-09 19:16:42 +01:00
|
|
|
cr.execute("drop database if exists " + dbname)
|
|
|
|
cr.execute("create database " + dbname)
|
2025-02-09 18:53:36 +01:00
|
|
|
|
|
|
|
cn.close()
|
|
|
|
|
|
|
|
cn = create_cn(hostname, port, password, username, dbname)
|
|
|
|
return cn
|
|
|
|
|
|
|
|
|
|
|
|
def create_cn(hostname, port, password, username, dbname):
|
|
|
|
"""Open connection to database.
|
|
|
|
|
|
|
|
:param hostname:
|
|
|
|
:param port:
|
|
|
|
:param password:
|
|
|
|
:param username:
|
|
|
|
:param dbname: string
|
|
|
|
:return: psycopg2.connection
|
|
|
|
|
|
|
|
"""
|
|
|
|
cn = pymysql.connect(
|
2025-02-09 19:16:42 +01:00
|
|
|
host=hostname, port=port, user=username, password=password, db=dbname, charset="utf8mb4", cursorclass=pymysql.cursors.DictCursor
|
2025-02-09 18:53:36 +01:00
|
|
|
)
|
|
|
|
|
|
|
|
return cn
|
|
|
|
|
|
|
|
|
2025-02-09 19:16:42 +01:00
|
|
|
def drop_db(hostname="localhost", port=3306, username=None, password=None, dbname=None):
|
2025-02-09 18:53:36 +01:00
|
|
|
"""Drop database.
|
|
|
|
|
|
|
|
:param hostname: string
|
|
|
|
:param port: int
|
|
|
|
:param username: string
|
|
|
|
:param password: string
|
|
|
|
:param dbname: string
|
|
|
|
|
|
|
|
"""
|
|
|
|
cn = pymysql.connect(
|
2025-02-09 19:16:42 +01:00
|
|
|
host=hostname, port=port, user=username, password=password, db=dbname, charset="utf8mb4", cursorclass=pymysql.cursors.DictCursor
|
2025-02-09 18:53:36 +01:00
|
|
|
)
|
|
|
|
|
|
|
|
with cn.cursor() as cr:
|
2025-02-09 19:16:42 +01:00
|
|
|
cr.execute("drop database if exists " + dbname)
|
2025-02-09 18:53:36 +01:00
|
|
|
|
|
|
|
close_cn(cn)
|
|
|
|
|
|
|
|
|
|
|
|
def close_cn(cn=None):
|
|
|
|
"""Close connection.
|
|
|
|
|
|
|
|
:param connection: pymysql.connection
|
|
|
|
|
|
|
|
"""
|
|
|
|
if cn:
|
|
|
|
cn.close()
|