xxxxxxxxxx
import mysql.connector
# Connect to the MySQL server
cnx = mysql.connector.connect(user='<username>', password='<password>',
host='<host>', database='<database>')
# Create a cursor object to execute the SQL queries
cursor = cnx.cursor()
# Execute the "SHOW DATABASES" query
cursor.execute("SHOW DATABASES")
# Fetch all the rows returned by the query
databases = cursor.fetchall()
# Print the names of the databases
for db in databases:
print(db[0])
# Close the cursor and connection
cursor.close()
cnx.close()
xxxxxxxxxx
mysql> SHOW DATABASES;
+--------------------+
| Database |
+--------------------+
| information_schema |
| mysql |
| performance_schema |
| pets |
| sys |
+--------------------+
5 rows in set (0.00 sec)
xxxxxxxxxx
import mysql.connector
# Connect to MySQL Server
connection = mysql.connector.connect(
host="localhost",
user="your_username",
password="your_password"
)
# Get list of all databases
cursor = connection.cursor()
cursor.execute("SHOW DATABASES")
# Print the list of databases
for database in cursor:
print(database[0])
# Close the cursor and connection
cursor.close()
connection.close()
xxxxxxxxxx
import mysql.connector
# Establish a connection to the MySQL database
connection = mysql.connector.connect(
host="YourHost",
user="YourUsername",
password="YourPassword",
database="YourDatabase"
)
# Create a cursor object to interact with the database
cursor = connection.cursor()
try:
# Getting all table names from the database
cursor.execute("SHOW TABLES")
tables = cursor.fetchall()
# Printing the table names
for table in tables:
print(table[0])
# Selecting data from a table
cursor.execute("SELECT * FROM your_table")
result = cursor.fetchall()
# Printing the retrieved data
for row in result:
print(row)
except mysql.connector.Error as error:
print("Error: {}".format(error))
# Close the cursor and the database connection
cursor.close()
connection.close()