You can even use fetchone() to get one row at a time. We use fetchall() function to get all rows of data. The above commands will run your SQL query and fetch its result. results = cursor.execute(query).fetchall() Next, we use the cursor object to execute the query, using execute command. You can change the following query as per your requirement. It also provides a cursor object used to send queries, fetch result and traverse it. The above lines will connect to your database and return a connection object that can be used to connect to database. host_name="localhost"Ĭonnection = db_nnect(host=host_name,user=db_user,password=db_password,database=db_name) We will use the connect() method to establish database connection, and pass the database user credentials as arguments. Replace the values of host_name, db_user, db_password, and db_name with your database’s host address, username, password and database name respectively. Next, add the following lines to connect to your database. #!/usr/bin/env pythonĭepending on the library you have installed, add the following line to import PostgreSQL connection library to your script. $ sudo vi db_query.pyĪdd the following lines to it, to set its execution environment. Next, run the following command to create empty python script. pip install psycopg2īoth these libraries provide the same functions to connect to database and execute SQL queries. Open terminal or command prompt and run the following command to install either of these libraries. Psycopg2 and pygresql are two popular libraries to connect to your database and execute SQL queries. Here are the steps to connect to PostgreSQL database using Python. How to Connect to PostgreSQL database using Python In this article, we will look at how to connect to PostgreSQL database using Python. Python provides many third-party libraries for it. Sometimes you may need to connect to PostgreSQL database from your python application and fetch data using SQL queries. Python is a popular language that allows you to perform many different tasks and build complex applications.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |