Here i describe the basics of connecting a MySQL server with python. I assume you're using python 3.5 or above. First things first; you should download and install appropriate MySQL python connector for Windows/Linux/Mac OSx from here. This is a long way to do job, you may and here i will use the pip Python Package Index and PyMySQL. You can install pip, by following the instructions. Open Windows PowerShell or Terminal in Linux and type;
pip install PyMySQL
After this pyMySQL installation you're ready to connect your MySQL server; first import pymysql.cursor
import pymysql.cursors
Connect to the database with your login credentials (Username, Password and Database Name);
connection = pymysql.connect(host='localhost',
user='test',
password='test',
db='test',
charset='utf8mb4',
cursorclass=pymysql.cursors.DictCursor)
The rest of the code; we will create a Table if not exist; named "users" with three columns Id, email and password. Create a new record and Read a single record;
try:
with connection.cursor() as cursor:
sql_0 = "CREATE TABLE IF NOT EXISTS `users` (`Id` INT NOT NULL AUTO_INCREMENT, `email` VARCHAR(500) NULL, `password` VARCHAR(500) NULL, PRIMARY KEY (`Id`)) COLLATE='utf8_general_ci' ENGINE=InnoDB;"
cursor.execute(sql_0)
sql_1 = "INSERT INTO `users` (`email`, `password`) VALUES (%s, %s)"
cursor.execute(sql_1, ('info@koraykaraman.com', 'very-secret'))
connection.commit()
with connection.cursor() as cursor:
sql = "SELECT `id`, `password` FROM `users` WHERE `email`=%s"
cursor.execute(sql, ('info@koraykaraman.com',))
result = cursor.fetchone()
print(result)
finally:
connection.close()
After execution IDLE should give this output;
{'id': 1, 'password': 'very-secret'}
You can download and run the python 3.5 code with your Python IDLE or directly from your Linux based OS, here you can find the instructions for how to run python codes in your Linux based OS.