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

Generate Parenthesis | Intuition + Code | Recursion Tree | Backtracking | Java

Problem Statement: Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses. Example…

2 months ago

Square Root of Integer

Given an integer A. Compute and return the square root of A. If A is…

1 year ago

Build Array From Permutation

Given a zero-based permutation nums (0-indexed), build an array ans of the same length where…

1 year ago

DSA: Heap

A heap is a specialized tree-based data structure that satisfies the heap property. It is…

1 year ago

DSA: Trie

What is a Trie in DSA? A trie, often known as a prefix tree, is…

1 year ago

Trees: Lowest Common Ancestor

What is the Lowest Common Ancestor? In a tree, the lowest common ancestor (LCA) of…

1 year ago