Saturday , September 18 2021
Home / Python / Python MySQL Create Database

Python MySQL Create Database

2 Python MySQL Create Database

Python MySQL Create Database

To create a database in MySQL, use the “CREATE DATABASE” statement:

Note: In MySQL, it’s mandatory to put a semicolon (;) at the end of a statement, which denotes the termination of a query. However, MySQL Connector/Python automatically appends a semicolon at the end of your queries, so there’s no need to use it in your Python code.

In [2]:
import mysql.connector
mydb = mysql.connector.connect(
  host="localhost",
  user="root",
  passwd=""
)
mycursor = mydb.cursor()
mycursor.execute("create database itronix")
  • To execute a SQL query in Python, you’ll need to use a cursor, which abstracts away the access to database records.
  • A query that needs to be executed is sent to cursor.execute() in string format.

Note: If the above code was executed with no errors, you have successfully created a database

Check if Database Exists

You can check if a database exist by listing all databases in your system by using the “SHOW DATABASES” statement:

In [3]:
import mysql.connector
mydb = mysql.connector.connect(
  host="localhost",
  user="root",
  passwd=""
)
mycursor = mydb.cursor()
mycursor.execute("show databases")

for x in mycursor:
    print(x)
('information_schema',)
('itronix',)
('mysql',)
('performance_schema',)
('phpmyadmin',)
('ritesh',)

You can also verify in browser by opening phymyadmin: http://localhost/phpmyadmin/

About Machine Learning

Check Also

Python MySQL Select From

5 Python MySQL Select From Python MySQL Select From Table¶To select from a table in …

Leave a Reply

Your email address will not be published. Required fields are marked *