Wednesday, June 8, 2022

How to connect to MySQL database in Python Ubuntu 20.04.4

Установить в Python venv 

$ pip3 install mysql-connector-python

***************************

Далее примеры кода

***************************

(.env) boris@boris-All-Series:~/MYSQL8029$ cat connectMySQL829.py

import mysql.connector

from mysql.connector import Error


try:

    connection = mysql.connector.connect(host='localhost',

                                         database='Electronics',

                                         user='root',

                                         password='*********')

    if connection.is_connected():

        db_Info = connection.get_server_info()

        print("Connected to MySQL Server version ", db_Info)

        cursor = connection.cursor()

        cursor.execute("select database();")

        record = cursor.fetchone()

        print("You're connected to database: ", record)


except Error as e:

    print("Error while connecting to MySQL", e)

finally:

    if connection.is_connected():

        cursor.close()

        connection.close()

        print("MySQL connection is closed")

(.env) boris@boris-All-Series:~/MYSQL8029$ vi connectMySQL829.py


(.env) boris@boris-All-Series:~/MYSQL8029$ python3 connectMySQL829.py

Connected to MySQL Server version  8.0.29-0ubuntu0.20.04.3

You're connected to database:  ('Electronics',)

MySQL connection is closed


(.env) boris@boris-All-Series:~/MYSQL8029$ cat createMySQL829.py

import mysql.connector


try:

    connection = mysql.connector.connect(host='localhost',

                                         database='Electronics',

                                         user='root',

                                         password='*********')


    mySql_Create_Table_Query = """CREATE TABLE Laptop ( 

                             Id int(11) NOT NULL,

                             Name varchar(250) NOT NULL,

                             Price float NOT NULL,

                             Purchase_date Date NOT NULL,

                             PRIMARY KEY (Id)) """


    cursor = connection.cursor()

    result = cursor.execute(mySql_Create_Table_Query)

    print("Laptop Table created successfully ")


except mysql.connector.Error as error:

    print("Failed to create table in MySQL: {}".format(error))

finally:

    if connection.is_connected():

        cursor.close()

        connection.close()

        print("MySQL connection is closed")

        

(.env) boris@boris-All-Series:~/MYSQL8029$ python3 createMySQL829.py

Laptop Table created successfully 

MySQL connection is closed














































No comments:

Post a Comment