Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 0968c2b

Browse files
fix spaces in codes
1 parent 2b93fd1 commit 0968c2b

File tree

1 file changed

+71
-46
lines changed

1 file changed

+71
-46
lines changed

‎README.md‎

Lines changed: 71 additions & 46 deletions
Original file line numberDiff line numberDiff line change
@@ -1,137 +1,162 @@
1-
21
# Connect PostgreSQL database with Python
32

43
In this section, I'll explain how to connect your PostgreSQL database to Python and query it.
54

6-
75
## Install "Psycopg2"
6+
87
To access the PostgreSQL database, Python needs a PostgreSQL driver. You must first install the `Psycopg2` package on your computer.
8+
99
```bash
10-
python -m pip install psycopg2
10+
python -m pip install psycopg2
1111
```
1212

1313
## Import Psycopg2"
14+
1415
To access the PostgreSQL database, import `psycopg2` library into your Python code.
16+
1517
```python
16-
import psycopg2
18+
import psycopg2
1719
```
1820

1921
## Creating a Database:
22+
2023
For the purpose of example, we will need a sample database. To do so, follow the below steps:
24+
2125
- First, open a PostgreSQL client tool like `pgadmin4` or `psql`.
2226
- Second login to the database using your credentials.
2327
- Finally, run the following command to create a database (for example, `company`).
28+
2429
```sql
25-
CREATE DATABASE company;
30+
CREATE DATABASE company;
2631
```
2732

2833
## Create Connection:
34+
2935
To connect to the above created database (i.e., `company`), we use the `connect()` function.
3036
So, establish a connection to the database. Use your PostgreSQL database's username and password in the Python code.
37+
3138
```python
32-
mydb = psycopg2.connect(
33-
host="localhost",
34-
user="yourUsername",
35-
password="yourPassword",
36-
database="company"
37-
)
39+
mydb = psycopg2.connect(
40+
host="localhost",
41+
user="yourUsername",
42+
password="yourPassword",
43+
database="company"
44+
)
3845
```
3946

4047
## Make Cursor:
48+
4149
You must create or include a `cursor()` in your Python code in order to run SQL queries.
50+
4251
```python
43-
mycursor = mydb.cursor()
52+
mycursor = mydb.cursor()
4453
```
54+
4555
Now you can use SQL commands to query the database.
4656

4757
## Commit Changes:
58+
4859
You also have to include the commit function and set automatic commit to be `true`.
60+
4961
```python
50-
mydb.set_session(autocommit=True)
62+
mydb.set_session(autocommit=True)
5163
```
64+
5265
So that each action is committed or saved without having to call `mydb.commit()` after each command.
5366

5467
## Query the Database:
68+
5569
Now create a table in the database using the cursor we created.
70+
5671
```python
57-
mycursor.execute('''CREATE TABLE employee(
58-
EmployeeID int,
59-
Name varchar(255),
60-
Email varchar(255));
61-
''')
72+
mycursor.execute('''CREATE TABLE employee(
73+
EmployeeID int,
74+
Name varchar(255),
75+
Email varchar(255));
76+
''')
6277
```
6378

6479
## Insert Data Into Table:
80+
6581
Now we are inserting the values into the database.
82+
6683
```python
67-
mycursor.execute('''
68-
INSERT INTO employee (EmployeeID, Name, Email)
69-
VALUES (101, 'Mark', 'mark@company.com'),
70-
(102, 'Robert', 'robert@company.com'),
71-
(103, 'Spencer', 'spencer@company.com');
72-
''')
84+
mycursor.execute('''
85+
INSERT INTO employee (EmployeeID, Name, Email)
86+
VALUES (101, 'Mark', 'mark@company.com'),
87+
(102, 'Robert', 'robert@company.com'),
88+
(103, 'Spencer', 'spencer@company.com');
89+
''')
7390
```
7491

7592
## Retrive the Data:
93+
7694
Now let’s query the database.
95+
7796
```python
78-
mycursor.execute("SELECT * FROM employee")
97+
mycursor.execute("SELECT * FROM employee")
7998
```
99+
80100
It’s important to note that after the query executes, you still need to use one of the `psycopg2` functions to retrieve data rows.
81101

82102
- fetchone()
83103
- fetchall()
84104
- fetchmany()
85105

86106
For example,
107+
87108
```python
88-
print(mycursor.fetchone())
109+
print(mycursor.fetchone())
89110
```
90-
| EmployeeID | Name | Email |
91-
| :--------- | :------- | :---------------- |
92-
| 101 | Mark | mark@company.com |
93111

94-
The most basic way to fetch data from your database is to use the `fetchone()` function. This function will return exactly one row (the first row) after executing the SQL query.
112+
| EmployeeID | Name | Email |
113+
| :--------- | :--- | :--------------- |
114+
| 101 | Mark | mark@company.com |
95115

116+
The most basic way to fetch data from your database is to use the `fetchone()` function. This function will return exactly one row (the first row) after executing the SQL query.
96117

97118
```python
98-
print(mycursor.fetchall())
119+
print(mycursor.fetchall())
99120
```
100-
| EmployeeID | Name | Email |
101-
| :--------- | :------- | :---------------- |
102-
| 101 | Mark | mark@company.com |
103-
| 102 | Robert | robert@company.com |
104-
| 103 | Spencer | spencer@company.com |
121+
122+
| EmployeeID | Name | Email |
123+
| :--------- | :------ | :------------------ |
124+
| 101 | Mark | mark@company.com |
125+
| 102 | Robert | robert@company.com |
126+
| 103 | Spencer | spencer@company.com |
105127

106128
If you need more than one row from your database, you can use `fetchall()`, which works the same as `fetchone()` except that it returns all the rows.
107129

108130
```python
109-
print(mycursor.fetchmany(2))
131+
print(mycursor.fetchmany(2))
110132
```
111-
| EmployeeID | Name | Email |
112-
| :--------- | :------- | :---------------- |
113-
| 101 | Mark | mark@company.com |
114-
| 102 | Robert | robert@company.com |
133+
134+
| EmployeeID | Name | Email |
135+
| :--------- | :----- | :----------------- |
136+
| 101 | Mark | mark@company.com |
137+
| 102 | Robert | robert@company.com |
115138

116139
With `fetchmany()`, you have another option to retrieve multiple records from the database and have more control over the exact number of rows retrieved.
117140

118-
You can use any of them depending on your needs.
141+
You can use any of them depending on your needs.
119142

120143
## Close the Connection:
144+
121145
In the end, you must close the cursor and the connection.
146+
122147
```python
123-
mycursor.close()
124-
mydb.close()
148+
mycursor.close()
149+
mydb.close()
125150
```
126151

127152
You can also get code snippet from [here](https://github.com/kishlayjeet/Connect-PostgreSQL-database-to-Python/blob/d7c5cae0a809ec0714cf193c5db6a77f30e70502/code-snippet.py).
128153

129154
## Authors
155+
130156
I am [Kishlay](https://www.github.com/kishlayjeet), and I have written this tutorial, but other people have also helped me with it.
131157
If you have any trouble with this tutorial, please tell me about it, and I will make it better.
132158
If you like this tutorial and this helped you out, then please give it a star.
133159

134160
## Feedback
135-
If you have any feedback, please reach out to me at contact.kishlayjeet@gmail.com
136-
137161

162+
If you have any feedback, please reach out to me at contact.kishlayjeet@gmail.com

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /