Python - MySQL Database Connection
MySQLdb is a python interface for connecting to a MySQL database server from Python. It implements the Python Database API (Application Programming Interface) Specification V2.0 and allows Python programmers to easily access a MySQL database server. MySQLdb is compatible with Python versions 2.4 through 2.7 and is written in C.
To check if a MySQL database exists using MySQLdb in Python, you can use the following code:
import MySQLdb
# Open database connection
db = MySQLdb.connect("localhost","username","password")
# prepare a cursor object
cursor = db.cursor()
# execute SQL query using execute() method and fetchone() method
cursor.execute("SELECT schema_name FROM information_schema.schemata WHERE schema_name = 'database_name'")
data = cursor.fetchone()
if data:
print("Database exists")
else:
print("Database does not exist")
# disconnect from server
db.close()
Replace "username" and "password" with your actual MySQL username and password, and replace "database_name" with the name of the database you want to check.
The code first opens a connection to the MySQL server using the connect() method, and then creates a cursor object using the cursor() method. The execute() method is used to execute a SQL query, and the fetchone() method retrieves the first row of the result set.
If the data variable is not empty, it means that the database exists, and the code prints "Database exists". Otherwise, it prints "Database does not exist". Finally, the code closes the database connection using the close() method.
To connect with MySQL using Python, you can use the MySQLdb module. Here is an example code for connecting to a MySQL database:
import MySQLdb
# Open database connection
db = MySQLdb.connect(host="localhost", user="username", passwd="password", db="database_name")
# disconnect from server
db.close()
In this example, you need to replace localhost, username, password, and database_name with your own values.