PostgreSQL (2) Database Connection With Python Using "Psycopg2" Module
ฝัง
- เผยแพร่เมื่อ 15 ม.ค. 2025
- Hello and welcome to the second video of PostgreSQL tutorial series.
Today you are going to learn how to connect PostgreSQL database to Python program.
As a matter of fact, there are several python modules that allow us to connect to and manipulate the database using PostgreSQL such as Psycopg2 which will be the module that we will be working with in this tutorial.
Download link: github.com/Bek...
Psycopg2 link: pypi.org/proje...
DEV profile : dev.to/bekbrace
Github profile: github.com/Bek...
Спасибо что так подробно. Такие как я имеют шанс чему-то научиться, благодаря таким как вы.
@@АркадийНалимов-р1э Огромное Спасибо 🙏
Thank you very much for this tutorial. Your teaching skill is really awesome.
Thank you Alamin, this means a lot to me, friend 😊
Hi @@BekBrace
Your Video is really helpful, i am able to connect to DB but while in main i am getting like this in Run
Connecting to postgreSQL Database ...
connect() argument after ** must be a mapping, not NoneType
Process finished with exit code 0
its the same code as yours, please help!
Wow, awesome tutorial video. I've watched hundreds of technical tutorials and I've never commented on one but this one was "the best." You nicely showed us how to connect a python script to Postgres using psycopg2. That's where everyone else would end their video. But then you threw it out and showed us that with a little more work, we could do it way better. Beautiful programming too. Even though you probably didn't make up the syntax, your explanation of why each part was necessary and shouldn't be different was superb. Liked and Subscribed
Thank you very very much for such kind words ! I appreciate you being a member of the family here, feel free always to ask your questions, and I will do my best to answer whenever possible. Thanks again my friend🙂
Thanx for a nice lesson and clear pronunciation which is easy-to-understand !
It’s a pleasure, Alex 🙏
Всегда с удовольствием 🙂
The ini approach is a pro move , thanks for the good job 👍
Thank you for watching 😊
Look forward for other sql parts , clear explaination , thxs alot
Thanks , sure there will be more on PostgreSQL , MySQL and SQL Alchemy
I'm a newbie. You left me in the dust on the config file...lolol But everything you said was clear to me. I just need to practice
Great stuff, my friend
hey im learning this now in 2024, how much did you progress in 3 years
@@rohitmalviya8607 what about you? did you get the code?
@@deshnajain1757 Ive been slacking since the last month never opened postgre after watching this video sorry
thanks for simple TuT, Great Going.
You're very welcome
thank u for the video and for your pronounciation, so easy to make out, thx
You're very welcome 🙏🙂
Nice work , thank you for sharing the knowledge
Glad it was useful 😊
I am at 10:22 , at line 20 in config.py , have you putted "config()" only because you have mentionned the filename and the section when you defined the function above ?
right ?
At line 20, you’re invoking the config() function; and by running the config.py file, it’s executed to call that config() function- but you can change both names, it will still work
@@BekBrace it wasn't my question. Actually , why is it possible to write the function with arguments and then call it without those arguments ; So what's the difference between a function with and without arguments in this case ?
@@ihebbibani7122 This has been 3 years, but for anyone reading this:
It is because he is setting default values for the parameters/arguments. So it is always 'database.ini' and 'postgresql' unless specified otherwise.
Bingo was his name
Wow very nice helpful 😀😇😜🤪😁
Glad you liked it
Quality video on PostgreSQL, tysm man
Thank you, Johanoid ,glad you found it useful.
incredibly helpful video. one question, to get the dictionary from the list of tuples around 9:10, why not simply do db = dict(parser.items(section)) ?
You can do that too 🙂
Thank you.. its worth watching your tutorials..
Much appreciated 👍
Thank you🥰🥰
You're welcome, Ahmed 🙂
I am new to postgresql, what is the point of connecting postgresql to python? thanks
Data Analysis: If you have data stored in a PostgreSQL database, you can use Python to connect to that database and extract, manipulate, and analyze the data. Python has powerful data analysis libraries like pandas, NumPy, and SciPy that can be used to perform complex data analysis tasks on the data stored in the PostgreSQL database.
Web Development: PostgreSQL is a popular choice for storing data in web applications, and Python is a popular language for web development. Connecting PostgreSQL to Python allows you to use Python's web development frameworks like Django and Flask to build web applications that interact with the database.
Automation: You can use Python to automate tasks that involve working with the PostgreSQL database. For example, you can write Python scripts that perform routine database maintenance tasks like backing up the database, checking for errors, and optimizing performance.
Machine Learning: Python is a popular language for machine learning and artificial intelligence, and PostgreSQL can be used to store large amounts of data that are used in these fields. By connecting PostgreSQL to Python, you can build machine learning models that use data stored in the database.
@@BekBrace Thanks a bunch sir
Thanks very much.
You're very welcome
Fantastic video! I was wondering how you enable the description of classes or hints or arguments that go in on VS code. Is this an extension or does it come natively with intellisense? If so please suggest how to enable it? Liked and subscribed!
Hi there! It's an installed plugin in VSCode called IntelliCode by Microsoft - download it for free.
Thank you for watching and being active on the channel - Also you can consider being a member of the channel to get free project assessments, debugging tips and code reviews.
what do i need to learn, if i am not getting why this code is put, and how it is done? prerquisite? i know basic python
@@deshnajain1757 oh. You should be familiar with database basics. I have a MySQL course you can check it out, then return back to this one
Thank you, Bek
Always a pleasure
Great video. Your explanations are great, thank you. Why does 'port' not need to be included in the database.ini file?
Thank you :) cause it's already defined ,🙂
Nice video. Your voice is a bit mesmeric, though :)
Thank you 😊 that’s not the first I hear that and I don’t know if it’s good or bad 😂
I am getting "Section postgresql is not found in the database.ini file" error even if I write everything right. I have checked thousand times. What could be the reason of this?
Have you “pip install configparser “ ? It’s a parser problem, Python cannot read what’s in your database.ini file
@@BekBrace I will try.
Btw thank you for the really quick reply. I would pay for the video and the service.
@@BekBrace I am getting same error after installing configparser as well
@@jijobuje i have the same problem
I'm using code from your github and it's working. I dont know how it's possible
i have a question how to open that 16:34
Open what ?
@@BekBrace the mingw64 cmd? Sorry im new to this
@@kotch1 oh no problem. That is git bash, go to Google and type download git bash, it's free and easy to use
@@BekBrace thank you sir!
Thanku good video. Have a doubt when i opened the site psycopg2 there could see the option pip install psycopg2 and when click on it only i get a copy option. And where i paste that link
To your command prompt or terminal to install psycopg2
would you consider moving the connection block of codes, above the MAIN, to another file and just invoke it in the Main.py ?
Nice video..
Yes, absolutely
Hey I am watching this video 3 years later and I like the concept but I am currently experiencing lots of errors when I run the main.py, connection to server at "localhost" (::1), port 5432 failed: FATAL: password authentication failed for user "postgresql" this is the error I keep experiencing.
Thanks in advance.
I tried doing what you suggested but I got an error after executing the config.py file. It says:
Traceback (most recent call last):
File "C:\Users\Janmielou\OneDrive\Documents\PostgresSQL\config.py", line 20, in
config()
File "C:\Users\Janmielou\OneDrive\Documents\PostgresSQL\config.py", line 15, in config
raise Exception('Section{0} is not found in the {1} file.'.format(section, filename))
Exception: Sectionpostgresql is not found in the database.ini file.
Add the [postgresql] section to your database.ini file with the required settings.
the installating is not working on my laptop
What’s the error ?
@@BekBrace I'm installing it on a Linux machine. The build wheels did not install properly. I installed the required dependencies but still got an error. So I installed it from the Github source to gett it working
@@BekBrace Also got this error
Traceback (most recent call last):
File "config.py", line 20, in
config()
File "config.py", line 11, in config
params = parser.items(section)
File "/usr/lib/python3.8/configparser.py", line 859, in items
return [(option, value_getter(option)) for option in orig_keys]
File "/usr/lib/python3.8/configparser.py", line 859, in
return [(option, value_getter(option)) for option in orig_keys]
File "/usr/lib/python3.8/configparser.py", line 855, in
value_getter = lambda option: self._interpolation.before_get(self,
File "/usr/lib/python3.8/configparser.py", line 395, in before_get
self._interpolate_some(parser, option, L, value, section, defaults, 1)
File "/usr/lib/python3.8/configparser.py", line 442, in _interpolate_some
raise InterpolationSyntaxError(
configparser.InterpolationSyntaxError: '%' must be followed by '%' or '(', found: '%'
from the config.py
thanks for the good job. I encountered such a problem. When I try to write the password wrong, print(error) is empty in the console. Why? postgres 10.15 psycopg2 2.8.6
Can you paste the debug report, please?
@@BekBrace I also only get an error if I use the wrong host, but not for wrong password or wrong database...
Thank you for making such a great video.
I encountered a problem with the main.py file. After running it I get the following error message:
Conecting to the postgreSQL database ...
invalid connection option "database"
Change database to dbname in your connection parameters.
really helpful, but i hope you can share the code since i found some mistake in my code (and i just know what the wrong until i found indent)
Thank You
Nice video! can you help me psycopg2 keeps giving me an error.
from psycopg2._psycopg import ( # noqa
......
)
ImportError: DLL load failed while importing _psycopg: The specified module could not be found.
it's a good video
Cheers
when i run the main.py file i get the following: {'host': 'localhost', 'database': 'master', 'user': 'postgres', 'password': 'admin'}
{'host': 'localhost', 'database': 'master', 'user': 'postgres', 'password': 'admin'}
Connecting to the postgreSQL database ...
psycopg2.connect() argument after ** must be a mapping, not NoneType
Make the function config() return db
Why not just use a .env file and then read the value with load_dotenv() and os.getenv("db_port")
You can.
There are a lot of ways to connect the server to python, however using ini file is just my preferred approach to do it especially if you want to deploy your app on Heroku for instance
@@BekBrace you're right , I have seen many githubs using your approach...
6 idiots 😝 dislike this great video !!
Thanks man
Gracias 🙏 well, that’s ok, everyone to their opinion but thanks my friend
Thank you very much for this tutorial. Your teaching skill is really awesome.
🙏🙏🙏