Output: Using Python variable in PostgreSQL select Query Print("PostgreSQL connection is closed \n") Print("Error fetching data from PostgreSQL table", error) PostgreSQL_select_Query = "select * from mobile where id = %s"Ĭursor.execute(postgreSQL_select_Query, (mobileID,)) import psycopg2Ĭonnection = Python variable in PostgreSQL select Query") To handle such requirements, we need to use a parameterized query.Ī parameterized query is a query in which we use placeholders ( %s) for parameters and the parameter values supplied at execution time. For example, the application can give any user id to get the user details. Most of the time, we need to pass Python variables as parameters to PostgreSQL queries to get the result. Read more: Python cursor’s fetchall(), fetchmany(), fetchone() to read records from database table Use Python variable as parameters in PostgreSQL Select Query cursor.fetchmany(SIZE) to fetch limited rows.Use the following methods of a cursor class to get a different result. Note: In the above example, we used a cursor.fetchall() to get all the rows of a database table. Output: Selecting rows from mobile table using cursor.fetchall Print("Error while fetching data from PostgreSQL", error) Print("Print each row and it's columns values")Įxcept (Exception, psycopg2.Error) as error: Print("Selecting rows from mobile table using cursor.fetchall") PostgreSQL_select_Query = "select * from mobile" Example to retrieve a row from PostgreSQL Table using fetchall() import psycopg2 Use cursor.clsoe() and connection.clsoe() method to close open connections after your work completes. Close the cursor object and database connection object.Iterate a row list using a for loop and access each row individually (Access each row’s column data using a column name or index number.) Execute the SELECT query using a execute() methodĮxecute the select query using the cursor.execute() method.Īfter successfully executing a Select operation, Use the fetchall() method of a cursor object to get all rows from a query result.Next, use a connection.cursor() method to create a Psycopg2 cursor object. If the where condition is used, then it decides the number of rows to fetch.įor example, SELECT col1, col2,…colnN FROM postgresql_table WHERE id = 5. You can select all or limited rows based on your need. Next, prepare a SQL SELECT query to fetch rows from a table. Refer to Python PostgreSQL database connection to connect to PostgreSQL database from Python using Psycopg2 module. How to Select from a PostgreSQL table using Python
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |