Getting the list of existing databases
We can get the list of all the databases by using the following
MySQL query.
1.
> show databases;
Example
1.
import mysql.connector
2.
3.
#Create the connection object
4.
myconn = mysql.connector.connect(host = "localhost", user = "root",passwd = "google")
5.
6.
#creating the cursor object
7.
cur = myconn.cursor()
8.
9.
try:
10. dbs = cur.execute("show databases")
11.
except:
12. myconn.rollback()
13.
for x in cur:
14. print(x)
15. myconn.close()
Output:
('EmployeeDB',)('Test',)('TestDB',)('information_schema',)('javatpoint',)('javatpoint1',)('mydb',)('mysql',)('performance_schema',)('testDB',)
Creating the new database
The new database can be created by using the following SQL
query.
1.
> create database <database-name>
Example
1.
import mysql.connector
2.
3.
#Create the connection object
4.
myconn = mysql.connector.connect(host = "localhost", user = "root",passwd = "google")
5.
6.
#creating the cursor object
7.
cur = myconn.cursor()
8.
9.
try:
10. #creating a new database
11. cur.execute("create database PythonDB2")
12.
13. #getting the list of all the databases which will now include the new database PythonDB
14. dbs = cur.execute("show databases")
15.
16.
except:
17. myconn.rollback()
18.
19.
for x in cur:
20. print(x)
21.
22. myconn.close()
Output:
('EmployeeDB',)('PythonDB',)('Test',)('TestDB',)('anshika',)('information_schema',)('javatpoint',)('javatpoint1',)('mydb',)('mydb1',)('mysql',)('performance_schema',)('testDB',)
0 Comments