#快速导入数据到postgresql

import pandas as pd

import psycopg2

from io import StringIO

def sql_to_df():

con=pymysql.connect(**conf["mysql_form"])

sql="select category_id,name,gameid,img_url from category where category_id in (11665,9653,6504) "

try:

with con.cursor() as cur:

cur.execute(sql)

datas=cur.fetchall()

finally:

con.close()

df=pd.DataFrame(list(datas))

return df

def df_to_pg(df=None,db="spider",table='price_730'):

#这里生成的StringIO类似于file文件,可read,可write,不同的是file是在硬盘上的文件,而StringIO是在内存中的文件

output=StringIO()

#也可以直接将字符串转换成内存文件 ,

#将数据保存到‘文件’

if not df :

df=sql_to_df()

df.to_csv(output,sep='\t',index=False,header=False)

#使文件定位到第一个字符

output.seek(0)

try:

conn=psycopg2.connect(database=db,**conf["postgres"])

cur=conn.cursor()

cur.copy_from(output,table,null='')

conn.commit()

result=cur.rowcount

finally:

cur.close()

conn.close()

return result

if __name__=='__main__':

# df=pd.read_csv('e:/730_price.csv')

print(df_to_pg(table="category"))

建立连接

使用*.ini文件(python的configparser包可以解析这种类型的配置文件)保存数据库连接的配置信息。

使用psycopg2.connect函数获得connection对象。

使用connection对象创建cursor对象。

使用cursor对象执行sql语句提交或者回滚transaction。

使用cursor对象fetchone获得查询结果。

关闭cursor对象和connection对象。

创建数据表

过程:

构造建表的sql语句

调用psycopg2.connect()方法获得connection对象

调用connection.cursor()方法获得cursor对象

调用cursor.execute()方法执行sql语句

调用connection.commit方法提交事务

调用cursor.close()和connection.close()方法关闭连接

插入行

构造插入语句, 使用%s作为占位符,执行时psycopg2会用值智能替换掉占位符。可以添加RETURNING字句,来得到自动生成的字段值。

同创建数据表的2,3。获得connection对象和cursor对象

使用cursor.execute方法来插入一行,使用cursor.executemany方法来插入多行。 execute方法的第一个参数是sql语句,第二个参数是值的tuple。executemany方法的第一个参数是sql语句,第二个参数是list of tuple。

如果在1中使用了RETURNING子句,可以使用cursor.fetchone方法,来获得返回的自动生成字段的值。

同上5

同上6

更新数据

基本上和插入行相同。

使用cursor.rowcount属性来获得受影响的行的数目。

transaction

connection对象负责管理事务。当你第一次使用cursor.execute方法执行sql语句的时候事务开启,这以后的所有sql语句都在这个事务中执行,直到connection.commit或者connection.rollback或者del connection或者connection.close被调用,事务才结束。

一个简单的select语句可能会开启一个事务并且对相应的表格加锁,所以如果你是在开发一个长时间运行的应用,而且一个连接长时间不使用,那么你需要调用commit或者rollback方法结束事务,避免不必要的问题。

使用connection.autocommit来控制事务

从psycopg2.5开始,connection和cursor都是context manager对象,可以在with ... as ...语句中使用。值得注意的是,离开with语句后,connection对象不会被close,它只是结束提交或者回滚事务。所以可以在多个with语句中使用connection对象。

调用存储过程

使用cursor.callproc('function name', tuple), 函数的第一个参数是存储过程的名字,函数的第二个参数是实参tuple。这个调用和cursor.execute('select * from functionanme(%s)', tuple)相同。

可以使用cursor.fetchone, cursor.fetchmany, cursor.fetchall来获得返回值。

blob对象

使用psycopg2.Binary对象和postgresql的BYTEA数据类型对应,用于存储二进制数据。

以下这个例子演示了二进制数据的存取。

config.py

de  >

def config():

db_conn_config = {

'host': 'localhost',

'user': 'postgres',

'password': '',

'dbname': 'test',

'port': 5432

}

return db_conn_config

de>

write_blob.py

de  >

import psycopg2

from config import config

def write_blob(path_to_file):

""" insert a BLOB into a table """

conn = None

try:

# read data from a picture

drawing = open(path_to_file, 'rb').read()

# read database configuration

params = config()

# connect to the PostgresQL database

conn = psycopg2.connect(**params)

# create a new cursor object

cur = conn.cursor()

# execute the INSERT statement

cur.execute("INSERT INTO parts_drawings(drawing_data,name) " +

"VALUES(%s,%s)",

(psycopg2.Binary(drawing), path_to_file))

# commit the changes to the database

conn.commit()

# close the communication with the PostgresQL database

cur.close()

except (Exception, psycopg2.DatabaseError) as error:

print(error)

finally:

if conn is not None:

conn.close()

if __name__ == '__main__':

write_blob('./1.jpg')de>

read_blob.py

de  >

from config import config

import psycopg2

def read_blob(id, path_to_dir):

""" read BLOB data from a table """

conn = None

try:

# read database configuration

params = config()

# connect to the PostgresQL database

conn = psycopg2.connect(**params)

# create a new cursor object

cur = conn.cursor()

# execute the SELECT statement

cur.execute(""" SELECT *

FROM parts_drawings

WHERE id = %s """,

(id,))

blob = cur.fetchone()

open(path_to_dir + str(blob[0]) + '.jpg', 'wb').write(blob[1])

# close the communication with the PostgresQL database

cur.close()

except (Exception, psycopg2.DatabaseError) as error:

print(error)

finally:

if conn is not None:

conn.close()

if __name__ == '__main__':

read_blob(1, './img/')

de>

查询数据

查询数据和其它操作类似。

可以使用cursor.fetchone, cursor.fetchall, cursor.fetchmany(size=cursor.arraysize)方法来返回查询结果。fetchone返回一个tuple或者None, fetchall返回一个list of tuple,如果没有结果则返回一个空的tuple。fetchmany返回list of tuple, list的长度由size参数决定,size的默认值是cursor.arraysize, 如果没有结果可以返回,那么返回一个空的list。

删除数据

和更新数据类似

可以使用cursor.rowcount来获得删除的行数目。

psycopg2 (python与postgresql)的更多相关文章

  1. Python:使用psycopg2模块操作PostgreSQL

    安装psycopg2模块: 怎么验证是否已经安装过psycopy2? 编写上面代码,运行看是否抛出缺少psycopg2模块. 安装方法1: 1)使用psycopg2-2.4.2.win-amd64-p ...

  2. python 安装PostgreSQL 模块:psycopg2

    官方资料:http://www.psycopg.org/psycopg/docs/ 安装: yum -y install python-psycopg2 (安装的版本可能是2.0) pip insta ...

  3. 9、Python 连接 PostgreSQL数据库 -- psycopg2

    1.cmd  pip install psycopg2 -- 提示错误信息 2.pip show pip   -->查看当前pip版本 3.python -m pip install --upg ...

  4. Python使用psycopg2模块操作PostgreSQL

    https://blog.csdn.net/pcent/article/details/78643611

  5. PostgreSQL连接python,postgresql在python 连接,创建表,创建表内容,插入操作,选择操作,更新操作,删除操作。

    安装 PostgreSQL可以用Python psycopg2模块集成. sycopg2是Python编程语言的PostgreSQL数据库的适配器. 其程序代码少,速度快,稳定.不需要单独安装这个模块 ...

  6. python连接postgresql数据库

    python可以通过第三方模块连接postgresql. 比较有名的有psycopg2  和python3-postgresql (一)psycopg2 ubuntu下安装 sudo apt-get ...

  7. python 操作PostgreSQL

    pip install psycopg Python psycopg2 模块APIs 以下是psycopg2的重要的的模块例程可以满足Python程序与PostgreSQL数据库的工作. S.N. A ...

  8. python连接postgreSQL

    利用python(我用的是python2.7版本)连接postgresql数据库,这里使用psycopg2这个插件 官网下载psycopg2-2.5.1.tar.gz:http://initd.org ...

  9. Python 操作 PostgreSQL 数据库

    我使用的是 Python 3.7.0 PostgreSQL可以使用psycopg2模块与Python集成. sycopg2是用于Python编程语言的PostgreSQL数据库适配器. psycopg ...

随机推荐

  1. Https流程,openssl本地自建证书,抓包

    HTTPS:超文本安全传输协议,和HTTP相比,多了一个SSL/TSL的认证过程,端口为443在http(超文本传输协议)基础上提出的一种安全的http协议,因此可以称为安全的超文本传输协议.http ...

  2. 将DevExpress.Utils.ImageCollection变量的image导出

    private void tspBtnExportExcel_Click(object sender, EventArgs e) { //暂时用来导出图片 string filePath = Syst ...

  3. UVA 11806 Cheerleaders (容斥原理

    1.题意描述 本题大致意思是讲:给定一个广场,把它分为M行N列的正方形小框.现在给定有K个拉拉队员,每一个拉拉队员需要站在小框内进行表演.但是表演过程中有如下要求: (1)每一个小框只能站立一个拉拉队 ...

  4. MVC ---- T4模板的小练习

    1.先建立两个模板文件 :Manger.ttinclude.DBHelper.ttinclude Manger.ttinclude <#@ assembly name="System. ...

  5. go 异常处理

    package main import "fmt" func main() { defer func() { if err := recover(); err != nil { f ...

  6. python 正则表达式替换字符串中匹配的字符

    import re street = '21 Ramkrishna Road' print(re.sub('Road$', 'Rd.', street)) 将结尾的Road用Rd.替换

  7. c++ 判断容器A是否是容器B的子集,如果是,返回true(includes)

    #include <iostream> // cout #include <algorithm> // includes, sort using namespace std; ...

  8. Bate冲刺四——《WAP团队》

    β冲刺第四天  1. 今日完成任务情况以及遇到的问题. ①马麒.杜有海:记录功能完善情况 ②郝明宇:记录验收情况 ③马宏伟.周欣:后台前端数据连接 ④乌勒扎:综合测试 2.成员时间贡献   成员 马宏 ...

  9. 难部署的taiga,式微的circus——趋势从进程管理到容器管理,简单才是美

    一直需要一个项目管理系统,一直没时间弄. taiga是github上搜project management star最多的项目,又是基于django用python写的后端,所以就用它: 但是,集中精力 ...

  10. 【转】ArcGIS API for Silverlight/WPF 2.1学习笔记(三)

    六.Feature Layer Feature Layer是一种特殊的Graphics layer(继承自Graphics layer),除了像Graphics layer一样包含和显示Graphic ...