spark + psycopg2+postgre 实现insert update 功能
来源:互联网 发布:淘宝自动优化标题软件 编辑:程序博客网 时间:2024/06/08 02:40
spark sql 主要是想了select 功能,不具备insert, update 功能,本文实现用spark + psycopg2对postgre 数据库进行insert update计算,代码部分已进行了详细的说明:
import psycopg2
import psycopg2.extras
from pyspark import SparkContext,SparkConf
from pyspark.sql import SQLContext
from pyspark.sql.types import Row, StructField, StructType, StringType, IntegerType
#opera: 对rdd中每一条记录进行操作
def opera(x):
newval = x[2]+ x[3]
return Row(id=x[0], name=x[1], val=newval)
#save_df_to_db:对rdd中的每一个partition进行处理
def save_df_to_db(records):
db_conn = psycopg2.connect(database="testdb", user="postgres", password="password", host="127.0.0.1", port="5432")
dict_cursor=db_conn.cursor()
upsert_query = "INSERT INTO t3 (id, name, val) VALUES (%(id)s, %(name)s, %(val)s) ON CONFLICT (id) DO UPDATE SET name = EXCLUDED.name,val=EXCLUDED.val;"
try:
dict_cursor.executemany(upsert_query, records)
except Exception as e:
print "Error in executing save_df_to_db: ", e.message
db_conn.commit()
db_conn.close()
#从数据库中获取需要的数据
conn = psycopg2.connect(database="testdb", user="postgres", password="password", host="127.0.0.1", port="5432")
cursor = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)
cursor.execute("SELECT t1.id , t2.name, t1.income, t2.val FROM t1 inner join t2 on t1.id = t2.id")
rows = cursor.fetchall()
#spark入口
sc = SparkContext(appName="PythonSQL")
#将数据库中的结果转化为rdd, 以进行后续操作
rdd = sc.parallelize(rows)
#数据处理
rdd2 = rdd.map(opera)
#写入数据库
rdd2.foreachPartition(save_df_to_db)
conn.close()
- spark + psycopg2+postgre 实现insert update 功能
- gridview 绑定数据.实现update、delete、insert into、分页功能
- SSIS 实现update,delete,insert
- 使用Merge Into 语句实现 Insert/Update
- 使用Merge Into 语句实现 Insert/Update
- mysql中实现insert or update
- pdo exec()函数实现insert update操作
- spark实现join功能
- SQL语言集数据查询、数据操纵、数据定义和数据控制功能于一体,语句INSERT、DELETE、UPDATE实现( )功能。
- Postgre中的 select for update 和 select for update nowait
- 两种使用Spring JdbcTemplate实现update或insert操作
- JavaBean 实现Mysql数据库操作(Query、Insert、Delete、Update)
- JavaBean 实现Mysql数据库操作(Query、Insert、Delete、Update)
- 实现MERGE操中获取UPDATE行数和INSERT行数
- php下 mysql实现拼接insert和update语句
- postgre实现树状结构查询
- oracle实现 无则insert插入,有则update更新,一条语句直接进行insert/update操作
- INSERT INTO UPDATE
- nginx中proxy_set_header Host $host的作用
- Qt Quick 图像处理实例之美图秀秀
- 欢迎使用CSDN-markdown编辑器
- 启动设备AR1失败,错误代码41,解决方法
- lombok的使用,简化代码又省力
- spark + psycopg2+postgre 实现insert update 功能
- 【C#】匿名函数使用
- python-open/文件操作
- Spring学习笔记1
- 一头扎进springboot之整合mybatis
- linux新建管理员用户
- Java程序员面试中的多线程问题
- 递归-无限极分类
- String、StringBuffer和StringBuilder的总结