Python Psycopg - 连接类
与 PostgreSQL 数据库实例的连接由连接类管理。它更像是一个数据库会话的容器。函数connect()用于创建与数据库的连接。 connect()函数启动一个新的数据库会话并返回一个连接类实例。我们可以通过使用连接对象来构造一个新的游标来执行任何 SQL 语句。
句法:
psycopg2.connect(database=”dbname”, user=’postgres’, password=passwords, host=local_host, port= port_number)
parameters:
- dbname =the database name
- user =user name used to authenticate (widely used= postgres)
- password= password
- host =database host address
- port =connection port number (defaults = 5432 )
例子:
我们导入 psycopg 包。 conn 是包含“课堂数据库”连接的连接变量,其中用户是“Postgres”,密码是“pass”,本地主机是“127.0.0.1”,端口号是“5432”。
Python3
# importing packages
import psycopg2
# forming connection
conn = psycopg2.connect(
database="Classroom",
user='postgres',
password='pass',
host='127.0.0.1',
port='5432'
)
Python3
# importing packages
import psycopg2
# forming connection
conn = psycopg2.connect(
database="Classroom",
user='postgres',
password='pass',
host='127.0.0.1', port='5432'
)
conn.autocommit = True
# creating a cursor
cursor = conn.cursor()
# list of rows to be inserted
sql = ''' create table Student_Details(student_id int, student_name varchar(30),
cgpa decimal)'''
# executing sql statement
cursor.execute(sql)
print('Table successfully created')
# list of rows to be inserted
values = [(12891, 'rachel', 9.5), (12892, 'ross', 8.93),
(12893, 'nick', 9.2)]
# executing the sql statement
cursor.executemany("INSERT INTO Student_Details1 VALUES(%s,%s,%s)", values)
# select statement to display output
sql1 = '''select * from Student_Details;'''
# executing sql statement
cursor.execute(sql1)
# fetching rows
for i in cursor.fetchall():
print(i)
# committing changes
conn.commit()
# closing connection
conn.close()
连接类中的方法
- cursor():连接是创建游标的原因。它们永久连接到连接,并且所有指令都在数据库会话的上下文中运行,都被连接覆盖。
Syntax:
cursor(name=None, cursor_factory=None, scrollable=None, withhold=False)
Parameters:
- name: by default “none”, if the name is given a server-side cursor will be returned, if none is given a regular client-side server will be returned.
- cursor_factory: to create non-standard cursors
- scrollable: default None
- withhold: default False
- commit(): commit() 是一种提交数据的方法。此方法通过向 Postgresql 服务器发送“COMMIT”语句来提交当前事务。因为默认情况下Python不会自动提交,所以在每个更改表数据的事务之后调用此方法是必要的。
语法:
connection.commit()
- rollback():它帮助我们回到任何待处理事务的开头。在没有首先提交或保存修改的情况下关闭连接将导致隐式回滚。
语法:
connection.rollback()
- close():此方法用于关闭与数据库的连接。
语法:
connection.close()
例子:
在下面的示例中,执行 create table 命令并使用 insert SQL 命令将值插入到表中。使用 commit() 方法保存更改。最后,使用 close() 方法关闭与数据库的连接。
Python3
# importing packages
import psycopg2
# forming connection
conn = psycopg2.connect(
database="Classroom",
user='postgres',
password='pass',
host='127.0.0.1', port='5432'
)
conn.autocommit = True
# creating a cursor
cursor = conn.cursor()
# list of rows to be inserted
sql = ''' create table Student_Details(student_id int, student_name varchar(30),
cgpa decimal)'''
# executing sql statement
cursor.execute(sql)
print('Table successfully created')
# list of rows to be inserted
values = [(12891, 'rachel', 9.5), (12892, 'ross', 8.93),
(12893, 'nick', 9.2)]
# executing the sql statement
cursor.executemany("INSERT INTO Student_Details1 VALUES(%s,%s,%s)", values)
# select statement to display output
sql1 = '''select * from Student_Details;'''
# executing sql statement
cursor.execute(sql1)
# fetching rows
for i in cursor.fetchall():
print(i)
# committing changes
conn.commit()
# closing connection
conn.close()
输出:
Table successfully created
(12891, 'rachel', Decimal('9.5'))
(12892, 'ross', Decimal('8.93'))
(12893, 'nick', Decimal('9.2'))