Everyone should know that python can operate a variety of databases, such as SQLite, MySql, and PostgreSQL. I will not repeat all database operation methods here, this document briefly introduces PostgreSQL used in the current project. it mainly describes how to connect Python to the PostgreSQL database. If you need it, you can refer to it for reference. let's take a look at it.
Preface
In fact, there are many modules in Python that can be used to connect to PostgreSQL. Here we recommend psycopg2. Psycopg2 is easy to install (pip install psycopg2
). Here we will focus on how to use it.
Connect to the database:
import psycopg2conn = psycopg2.connect(host="10.100.157.168",user="postgres",password="postgres",database="testdb")
Available parameters during connection:
Dbname-database name (dsn connection mode)
Database-database name
User-user name
Password-password
Host-server address (if no default Unix Socket is provided)
Port-connection port (5432 by default)
Execute SQL
Import psycopg2 conn = psycopg2.connect (host = "10.100.157.168", port = 5432, user = "s", password = "postgres", database = "testdb") cur = conn. cursor () SQL = "" cur.exe cute (SQL) conn. commit () # No need to query. this method commits the current transaction. If you do not call this method, no matter what changes have been made, since the last call # commit () is invisible conn. close ()
In addition, parameterization is supported during SQL execution.
Syntax: cursor.execute(sql [, optional parameters])
Case: cursor.execute("insert into people values (%s, %s)", (who, age))
Summary
The above is all about this article. I hope this article will help you in your study or work. if you have any questions, please leave a message.