PYTHON Tutorial

Setting up MySQL

Installing MySQL

Windows:

  • Download the MySQL installer from the official website.
  • Run the installer and follow the on-screen instructions.

Linux (Ubuntu):

  • Open a terminal and run: sudo apt-get update
  • Install MySQL: sudo apt-get install mysql-server

MacOS:

  • Install Homebrew: brew install mysql

Configuring MySQL

Start the MySQL server:
// For Windows
net start mysql

// For Linux/Mac
sudo service mysql start
Open the MySQL configuration file:
// For Windows
C:\ProgramData\MySQL\MySQL Server 8.0\bin\my.ini

// For Linux/Mac
/etc/mysql/my.cnf
Edit the file to modify settings such as:
// Port
port = 3306

// Data directory
datadir = /var/lib/mysql
Save and close the file.

Starting MySQL Server

// For Windows
net start mysql

// For Linux/Mac
sudo service mysql start

Creating a Database

  • Connect to MySQL using mysql -u root -p
  • Create a database: CREATE DATABASE my_database;

Example in Python

import mysql.connector

# Connect to MySQL
db = mysql.connector.connect(
    host='localhost',
    user='root',
    password='password',
    database='my_database'
)

# Create a cursor
cursor = db.cursor()

# Execute a query
cursor.execute("SELECT * FROM my_table")

# Fetch results
results = cursor.fetchall()

# Close cursor and connection
cursor.close()
db.close()