Thursday, September 1, 2022

Calling MySQL Stored Procedures from Python 3.10.4

 (.env) boris@boris-All-Series:~/MYSQL$ mysql -u root -p

Enter password: 

Welcome to the MySQL monitor.  Commands end with ; or \g.

Your MySQL connection id is 28

Server version: 8.0.30-0ubuntu0.22.04.1 (Ubuntu)

Copyright (c) 2000, 2022, Oracle and/or its affiliates.

Oracle is a registered trademark of Oracle Corporation and/or its

affiliates. Other names may be trademarks of their respective

owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.


mysql> use  Electronics ;

Reading table information for completion of table and column names

You can turn off this feature to get a quicker startup with -A

Database changed

mysql> desc laptop ;

+---------------+--------------+------+-----+---------+-------+

| Field         | Type         | Null | Key | Default | Extra |

+---------------+--------------+------+-----+---------+-------+

| Id            | int          | NO   | PRI | NULL    |       |

| Name          | varchar(250) | NO   |     | NULL    |       |

| Price         | float        | NO   |     | NULL    |       |

| Purchase_date | date         | NO   |     | NULL    |       |

+---------------+--------------+------+-----+---------+-------+

4 rows in set (0,01 sec)


mysql> DELIMITER //

mysql> CREATE PROCEDURE get_laptop(IN d-id int)

    -> BEGIN

    -> select * from laptop where Id = d_id;

    -> END //

Query OK, 0 rows affected (0,12 sec)


На основании mysql> desc laptop можно просто сфомировать заголовок в Пайтон

(.env) boris@boris-All-Series:~/MYSQL$ cat storedPython1.py

import mysql.connector as myconn

mydb = myconn.connect(

    host="localhost",

    user="root",

    password="************",

    database="Electronics"

)

obj = mydb.cursor()

obj.callproc("get_laptop", [4])


for result in obj.stored_results():

    details = result.fetchall()


print("============================================================")

print("Id   Name                Price   Purchase_date              ")

print("============================================================")

for det in details:

    print(det)


obj.close()

mydb.close()

(.env) boris@boris-All-Series:~/MYSQL$ python3 storedPython1.py

================================================

Id   Name                         Price      Purchase_date              

================================================

(4, 'HP Pavilion Power', 1999.0, datetime.date(2019, 1, 11))





























































No comments:

Post a Comment