Python Forum
connection python and SQL - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: connection python and SQL (/thread-41270.html)



connection python and SQL - dawid294 - Dec-11-2023

Hi python experts, Is possible to connect Python and SQL? In jupyter notebook or in Pycharm? Is possible start the code from SQL in Python? If Yes how?Thanks


RE: connection python and SQL - buran - Dec-11-2023

Could you elaborate? It's not clear what you ask. Of course it's possible to interact with a DB from/via python code


RE: connection python and SQL - dawid294 - Dec-11-2023

ok i have created the code in PL/SQL developer where i download and edit the data, after that I save this data to excel and after that I start The code with model in python. I would like to improve this process and use only Python, because the SQL code still will the same and I would like to save my time. But I do not know how can i do this which programme i have to use. Thanks


RE: connection python and SQL - buran - Dec-11-2023

Still not sure if you want to rewrite some parts in python or just call PL/SQL from python.
Maybe have a look ate https://python-oracledb.readthedocs.io/en/latest/user_guide/plsql_execution.html


RE: connection python and SQL - Pedroski55 - Dec-12-2023

I think it is a good idea to access the database using phpMyAdmin first. Make an SQL query and try it, to make sure that it works. When you know you have a query that works, then you can do it from Python.

I only do simple stuff. For me, pymysql works fine.

import pymysql 

def mysqlINSERT(name, email, comment): 
    conn = pymysql.connect( 
        host='127.0.0.1', 
        user='baby',  
        password = 'Taizhou', 
        db='babydb', 
        )        
    cur = conn.cursor() 
    # INSERT query 
    command = 'INSERT INTO agro_products (customer_id, product_name, product_class) VALUES (%s, %s, %s)'
    cur.execute(command, (name, email, comment))
    # without conn.commit() all you get is simulation, nothing is actually written
    conn.commit()
    # To close the connection 
    conn.close()
    return 'OK'

name = 'Use me'
email = '[email protected]'
comment = 'Hope this kills everything!'
doit = mysqlINSERT(name, email, comment)
Here is a query to return the column names of a given table:

Quote:SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = 'babydb' AND TABLE_NAME = 'agro_products';

Try it in phpMyAdmin first, using your database name and table name, of course. When you know it works, try it in Python.