Categories: python

Create Database-Python MySQL

To create a new MySQL database in Python, you can use the mysql-connector-python library to connect to the MySQL server and issue a CREATE DATABASE statement.

Create Database:

The basic syntax of the create database statement:

CREATE DATABASE database_name
Example:

Here is an example:

import mysql.connector

mydb = mysql.connector.connect(
    host="hostname",
    user="username",
    password="password"
)

mycursor = mydb.cursor()

mycursor.execute("CREATE DATABASE mydatabase")

In this example, host, user, and password should be replaced with the appropriate values for your MySQL server. Also, mydatabase should be replaced with the desired name for the new database.

List all databases:

To list all databases in a MySQL server using Python, you can use the mysql-connector-python library to connect to the MySQL server and issue a SHOW DATABASES statement.

Here is an example:
import mysql.connector

mydb = mysql.connector.connect(
    host="hostname",
    user="username",
    password="password"
)

mycursor = mydb.cursor()

mycursor.execute("SHOW DATABASES")

for x in mycursor:
    print(x)

In this example, host, user, and password should be replaced with the appropriate values for your MySQL server.

The for loop will iterate through the results of the SHOW DATABASES statement and print the name of each database.

Note: you need to have appropriate privileges to list all databases, otherwise it will give an error.

Note: also read about MySQL with Python

Follow Me

Please follow me to read my latest post on programming and technology if you like my post.

https://www.instagram.com/coderz.py/

https://www.facebook.com/coderz.py

Recent Posts

Find Intersection of Two Singly Linked Lists

You are given two singly linked lists that intersect at some node. Your task is…

1 month ago

Minimum Cost to Paint Houses with K Colors

A builder plans to construct N houses in a row, where each house can be…

2 months ago

Longest Absolute Path in File System Representation

Find the length of the longest absolute path to a file within the abstracted file…

2 months ago

Efficient Order Log Storage

You manage an e-commerce website and need to keep track of the last N order…

3 months ago

Select a Random Element from a Stream

You are given a stream of elements that is too large to fit into memory.…

3 months ago

Estimate π Using Monte Carlo Method

The formula for the area of a circle is given by πr². Use the Monte…

3 months ago