Spark与jdbc连接Postgre库(scala代码实现)

  在开发spark应用过程中,遇到需要连接postgres库的场景,进行增删改查操作。可以通过原生的jdbc去连接pg库,也可以使用spark直连pg库作增删改查操作,代码均是用scala写的。

1.原生jdbc连接

下面是 通过DriverManager连接pg

try{
// 将“用户名、密码”加入properties
val conn_prop = new Properties()
conn_prop.put("user","xxxx")
conn_prop.put("password","xxxx")
//pg库的连接串:'xxxx'是库名
val conn_url = "jdbc:postgresql://127.0.0.1:5432/xxxx"
//创建pg数据库连接
val con:Connection = DriverManager.getConnection(conn_url,conn_prop )
//创建statement
//查询statement
val query_stm:Statement = con.createStatement()
val rs1= query_stm.excuteQuery("select id,name,money from test_zero where id<1")
while(rs1.next()){
	val r_id = rs1.getInt("id")
	val r_name = rs1.getString("name")
	val r_sex = rs1.getDouble("money")
	println(r_id+","+r_name+","+r_money)
}
//更新statement
val update_stm:Statement = con.createStatement()
val rs2 = update_stm.excuteUpdate("update test_zero set name='zero_update',money=100000.00 where name='zero'")
}
finally{
   //关闭连接
   conn.close()
}

2.spark直连

下面是 通过Spark直接连接pg,有两种方式
  方式一:sparkSession.read.jdbc(url,table,properties)
  方式二:sparkSession.read.format(“jdbc”).option("","").load()

//创建sparkSession
val conf  = new SparkConf().setAppName("conncetPG").setMaster("local[*]")
val spark = SparkSession.builder().config(conf).getOrCreate()
/**
 * 第一种:spark.read.jdbc()
 */
//将“用户名、密码、驱动类”加入properties类
val conn_prop = new Properties()
conn_prop.put("user","xxxx")
conn_prop.put("password","xxxx")
conn_prop.put("driver","org.postgresql.Driver")
//连接pg库,将properties参数和待查询的表一并传入,生成结果dataframe
val df1 = spark.read.jdbc(url="jdbc:postgresql://127.0.0.1:5432/xxxx",table="test_zero",conn_prop)
//对结果dataFrmae进行查询操作
df.select("id","name","money").show()
/**
 * 第二种:spark.read.format("jdbc").option("","").load()
 */
 //将数据库相关参数直接以.option()方式传入sparksession,然后load结果生产dataframe
 val df2 = spark.read
 		.format("jdbc")
 		.option("url","jdbc:postgresql://127.0.0.1:5432/xxxx")
 		.option("dbtable","test_zero")
 		.option("user","xxxx")
 		.option("password","xxxx")
 		.load()
 //对结果表dataframe进行过滤查询操作
 val n_df2 = df2.select("id","name","money").filter("name='zero'")
 /**
 * 另外可以将查询结果dataframe创建成临时表,这样就可以使用纯hive-sql的方式进行查询操作
 * 例如:sparkSession.sql("query_sql")
 */
 //创建临时表,这样可以直接使用spark.sql()
 n_df2.createOrReplaceTempView("tmp_test_zero")
 //执行sparksql
 spark.sql("select * from tmp_test_zero where name like '%zero%'").show()



  • 1
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论
### 回答1: 好的,我可以帮你写一个Python连接Postgre数据并将结果写入MySQL代码。在写代码之前,我们需要确保你已经安装了以下几个模块: 1. psycopg2 - 用于连接PostgreSQL数据的模块 2. MySQL Connector - 用于连接MySQL数据的模块 在安装这两个模块之后,我们就可以开始写代码了。首先,我们需要连接PostgreSQL数据,然后执行一条SQL语句。下面是连接PostgreSQL数据并执行SQL语句的代码: ```python import psycopg2 # 连接PostgreSQL数据 conn = psycopg2.connect( host="localhost", database="mydatabase", user="user", password="password" ) # 创建游标 cur = conn.cursor() # 执行SQL语句 cur.execute("SELECT * FROM mytable") # 获取SQL查询的结果 result = cur.fetchall() # 关闭游标和连接 cur.close() conn.close() ``` 接下来,我们需要连接MySQL数据,并将PostgreSQL查询的结果写入MySQL。下面是连接MySQL数据并将数据写入的代码: ```python import mysql.connector # 连接MySQL数据 conn = mysql.connector.connect( host="localhost", database="mydatabase", user="user", password="password" ) # 创建游标 cur = conn.cursor() # 将PostgreSQL查询的结果写入MySQL for row in result: cur.execute("INSERT INTO mytable (column1, column2, column3) VALUES (%s, %s, %s)", row) # 提交事务 ### 回答2: 当然可以!以下是一个示例代码,你可以根据你的实际需求进行相应的修改: ```python import psycopg2 import pymysql # 连接Postgre数据 pg_conn = psycopg2.connect( host="localhost", database="postgres", user="postgres", password="your_password" ) # 连接MySQL数据 mysql_conn = pymysql.connect( host="localhost", user="your_username", password="your_password", database="your_database_name" ) # 创建Postgre数据游标 pg_cursor = pg_conn.cursor() # 执行SQL语句 pg_cursor.execute("SELECT * FROM your_postgre_table") # 获取查询结果 results = pg_cursor.fetchall() # 创建MySQL数据游标 mysql_cursor = mysql_conn.cursor() # 插入数据到MySQL数据 for row in results: mysql_cursor.execute( "INSERT INTO your_mysql_table (column1, column2, column3) VALUES (%s, %s, %s)", (row[0], row[1], row[2]) ) # 提交事务 mysql_conn.commit() # 关闭连接 pg_cursor.close() pg_conn.close() mysql_cursor.close() mysql_conn.close() ``` 请将上述代码中的"your_password","your_username","your_database_name","your_postgre_table","your_mysql_table"替换为你实际的信息。 此代码示例假设你已经正确安装并配置好了`psycopg2`和`pymysql`。如果没有安装,请使用以下命令进行安装: ``` pip install psycopg2 pip install pymysql ``` 希望以上代码对你有帮助!如果还有其他问题,请随时提问。 ### 回答3: 可以的,以下是一个示例代码: ```python import psycopg2 import mysql.connector # 连接PostgreSQL数据 postgre_conn = psycopg2.connect( host='localhost', port='5432', database='your_postgre_database', user='your_postgre_user', password='your_postgre_password' ) # 连接MySQL数据 mysql_conn = mysql.connector.connect( host='localhost', port='3306', database='your_mysql_database', user='your_mysql_user', password='your_mysql_password' ) # 创建PostgreSQL数据游标 postgre_cursor = postgre_conn.cursor() # 执行SQL语句查询PostgreSQL数据 sql_query = "SELECT * FROM your_table" postgre_cursor.execute(sql_query) result = postgre_cursor.fetchall() # 创建MySQL数据游标 mysql_cursor = mysql_conn.cursor() # 创建表格用于存储查询结果 mysql_cursor.execute("CREATE TABLE your_table (column1 datatype, column2 datatype, ...)") # 将查询结果插入MySQL数据表格 for row in result: mysql_cursor.execute("INSERT INTO your_table (column1, column2, ...) VALUES (%s, %s, ...)", row) # 提交事务并关闭连接 mysql_conn.commit() postgre_cursor.close() mysql_cursor.close() postgre_conn.close() mysql_conn.close() ``` 请根据实际情况替换示例代码中的数据连接参数和要执行的SQL语句,并根据需要修改表格和列名。注意确保已安装`psycopg2`和`mysql-connector-python`模块。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

ZeroXu0

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值