query = """ SELECT * FROM bigenergystorage.cubede1.event20240822 where where…
- User
query = """ SELECT * FROM
bigenergystorage.cube_de1.event_20240822where where connectionDeviceId=='DE1_0002' and recordTime>'2024-08-22 02:00:00' order by recordTime asc; """rawData = spark.sql(query)
rawData = rawData.select( col("projectType").alias("stationId"), col("connectionDeviceId"), col("cloudName").alias("eventType"), col("listIndex").alias("eventIndex"), col("bitNum"), col("bitValue"), to_timestamp(col("recordTime"), "yyyy-MM-dd'T'HH:mm:ss.SSSX").alias("recordTime") )
def write_to_sql_server_table(batch_df): try: conn = jaydebeapi.connect(jdbc_driver, jdbc_url, [jdbc_username, jdbc_password]) cursor = conn.cursor()
sorted_batch_df = batch_df.sort(col("recordTime").asc()) for row in sorted_batch_df.rdd.collect(): standard_time = row["recordTime"].strftime("%Y-%m-%d %H:%M:%S") sql_query = f""" EXEC ProcessEventInfoData '{row["stationId"]}', '{row["connectionDeviceId"]}', '{row["eventType"]}', {row["eventIndex"]}, {row["bitNum"]}, {row["bitValue"]}, '{standard_time}' """ # print(f"{sql_query}") cursor.execute(sql_query) conn.commit() except Exception as e: print(f"Error processing batch {batch_id}: {e}") finally: cursor.close() conn.close() write_to_sql_server_table(rawData) 对这个代码优化,提升写入数据库速度 - Assistant