How to create and show table in mysql database using python on CentOS and RHEL 6/7 step by step guide
In this
article we will learn how to create mysql table in database using python language.
We need to
install the mysql.connector module using the below command.
#pip3 install
mysql.connector
Normally we
create mysql table into database using “create
table” statement and select the database in which mysql table will be
created.
How to create mysql table into databse using python
First we
need to create one file named createtable.py
and enter the below code into this file
.
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="root",
passwd="abc123",
database=” pythonclass”
)
cur = mydb.cursor()
cur.execute("CREATE TABLE student (name VARCHAR(30),
location VARCHAR(100))")
How to execute the python progam
To execute
the python program we need to execute the below command.
[root@localhost ~]# python3 createtable.py
After executing the
above command new table has been created.
Now enter the mysql
promt and verify it is created or not using “show tables” statement.
mysql> show tables;
+-----------------------+
|
Tables_in_pythonclass |
+-----------------------+
|
student |
+-----------------------+
1 row in
set (0.00 sec)
How to create and show table in mysql database using python on CentOS and RHEL 6/7 step by step guide |
How to view mysql database table using python
We also can check created
table list using python program.
We create one file
name showtable.py and enter the
below command.
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="root",
passwd="abc123"
database=”pythonclass”
)
cur = mydb.cursor()
cur.execute("SHOW TABLES")
for x in cur:
print(x)
That’s all. If this
article is helpful please share it!!!!
0 comments:
Post a Comment