How to Check If a Database Exists By Listing All Databases in Python


In this example we will show how to check if a database exists by listing all databases in your system in Python MongoDB.

Source Code

from pymongo import MongoClient

client = MongoClient('localhost', 27017)

print(client.list_database_names())

Output:

['admin', 'config', 'local', 'mydatabase']
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments

How to Check If a Database Exists By Listing All Databases in Python


In this example we will show how to check if a database exists by listing all databases in your system in Python.

Source Code

import mysql.connector

# connect to server
mydb = mysql.connector.connect(
    host="localhost",
    port=3306,
    user="yourusername",
    password="yourpassword"
)

# get a cursor
mycursor = mydb.cursor()

# execute a query
mycursor.execute("SHOW DATABASES")

for item in mycursor:
    print(item)

Output:

('information_schema',)
('mydatabase',)
('mysql',)
('performance_schema',)
('phpmyadmin',)
('python',)
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments