python连接数据库

python连接postgresql数据库

postgresql是常用的关系型数据库,并且postgresql目前还保持着全部开源的状态,所以我们今天就一起来学习一下,如何用python连接postgresql。

安装psycopg

pip install psycopg2

python连接sql数据库

安装pymysql

pip install pymysql

python连接oracle数据库

安装cx_Oracle

 pip install cx_Oracle 

连接数据库操作流程

若是增、删、更等操作,则操作流程为:

connect连接
获取游标对象cursor
执行sql得到结果execute
操作成功执行提交commit
关闭连接释放资源

import psycopg2
## 建立connect 连接
conn = psycopg2.connect(database='test',user='postgres',password='xxxxxx',host='localhost',port='5432')

# 游标
cur = conn.cursor()

# 执行sql
# 建表
cur.execute('create table tname(id int,name varchar);')
# 插入数据
cur.execute('insert into tname values (1,\'张三\');');
t_table=((2,'李四'),(3,'王五'))/[(2,'李四'),(3,'王五')]
cur.executemany('insert into tname values (%s,%s)',t_table)

# 提交数据
conn.commit()

# 关闭连接
conn.close()

若是查询,则操作流程为:

connect连接
获取游标对象cursor
执行sql得到结果 execute
获取数据
关闭连接释放资源


import psycopg2
## 建立connect 连接
conn = psycopg2.connect(database='test',user='postgres',password='xxxxxx',host='localhost',port='5432')

# 游标
cur = conn.cursor()

# 执行sql
cur.execute('select * from tname;')

# 获取数据
rows = cur.fetchall()
for row in rows:
    print(row)


# 关闭连接
conn.close()

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

友情链接更多精彩内容