9951 explained code solutions for 126 technologies


python-mysqlHow can I create a web application using Python and MySQL?


To create a web application using Python and MySQL, you can use the Python web framework Django. You will need to install Django and MySQL on your computer.

Example code block to create a database:

import MySQLdb

#Create a connection to the MySQL server
db = MySQLdb.connect(
    host="localhost",
    user="root",
    passwd="password",
    database="my_db"
)

#Create a cursor object
cursor = db.cursor()

#Create a database
cursor.execute("CREATE DATABASE my_db")

Output example

None

Code explanation

  • import MySQLdb: imports the MySQLdb module which is used to connect to a MySQL database.
  • db = MySQLdb.connect(): creates a connection to the MySQL server.
  • cursor = db.cursor(): creates a cursor object which is used to execute SQL commands.
  • cursor.execute("CREATE DATABASE my_db"): creates a database with the name my_db.

List of ## Helpful links

Edit this code on GitHub