The 7 Things I Know About Cyber Security After 25 Years | April 2024
Python database connection
1.
2. Disclaimer: This presentation is prepared by trainees of
baabtra as a part of mentoring program. This is not official
document of baabtra –Mentoring Partner
Baabtra-Mentoring Partner is the mentoring division of baabte System Technologies Pvt .
Ltd
4. Introduction
• Psycopg2 is the most popular PostgreSql adapter
for the Python programming language
• core it fully implements the pythondb API 2.0
• Install the Psycopg2
Command for installation:
• sudo apt-get install python-psycopg2
Creating user
Here we install the psycopg2 module on a Ubuntu
system.
$ sudo -u postgres createuser janbodnar Shall the
new role be a superuser? (y/n) y
5. Steps:
1) We want to import psycopg2 in code
Import psycopg2
2) Connect to an existing database
conn = psycopg2.connect("dbname=test
user=postgres")
cur=conn.cursor()
3) Execute a command: this creates a new table
cur.execute("CREATE TABLE test (id serial PRIMARY
KEY, num integer, data varchar);")
6. • Query the database and obtain data as Python
objects
cur.execute("SELECT * FROM test;")
cur.fetchone() (1, 100, "abc'def")
4) Make the changes to the database persistent
conn.commit()
5) Close communication with the database
conn.close()
7. • The function connect() creates a new database
session and returns a new connection instance.
• The class connection encapsulates a database
session. It allows to:
create new cursor using the cursor()method to
execute database commands and queries,
terminate transactions using the methods
commit()or rollback()
8. .
• The class cursor allows interaction with the
database:
---send commands to the database using methods
such as execute() and executemany()
---retrieve data from the database by iteration or
using methods such as fetchone(), fetchmany(),
fetchall().
9. Example:
import psycopg2
try:
con=psycopg2.connect("dbname = testdb user = shafeequemonp'")
cur=con.cursor()
cur.execute('SELECT version()')
ver=cur.fetchone()
print ver
except psycopg2.DatabaseError.e:
print 'Error %s' % e
sys.exit(1)
finally:
if con:
con.close()
10. If this presentation helped you, please visit our
page facebook.com/baabtra and like it.
Thanks in advance.
www.baabtra.com | www.massbaab.com |www.baabte.com
11. Contact Us
Emarald Mall (Big Bazar Building)
Mavoor Road, Kozhikode,
Kerala, India.
Ph: + 91 – 495 40 25 550
NC Complex, Near Bus Stand
Mukkam, Kozhikode,
Kerala, India.
Ph: + 91 – 495 40 25 550
Start up Village
Eranakulam,
Kerala, India.
Email: info@baabtra.com