With pyspark sql functions, I'm trying to do this
from pyspark.sql import functions as sf
query = sf.concat(sf.lit("UPDATE abc"), sf.lit(" SET col1= '"), sf.col("col1"), sf.lit("'"), sf.lit(", col2= '"), sf.col("col2"), sf.lit("'"), sf.lit(" WHERE col3 = 1")
myDataframe = myDataframe.withColumn("query", query)
query_collect = myDataframe.collect()
conn = createConnexion(args, username, password)
try:
for row in query_collect:
print(row["query"])
conn.run(row["query"])
conn.commit()
But it doesn't works. It work with just col1, but col2 make an error because sometime, this col2 is empty (null) query column is null and conn.run(row["query"]) throw this exception : None 'NoneType' object has no attribute 'encode'
I'm trying to use pyspark sql.when like this but this is the same issue :
myDataframe = myDataframe.fillna(value="NO_SQL")
query = sf.concat(sf.lit("UPDATE abc"),
sf.lit(" SET col1= '"),
sf.col("col1"),
sf.lit("'"),
sf.when(sf.col("col2") != "NO_SQL", sf.concat(sf.lit(", col2= '"), sf.col("col2"), sf.lit("'"))),
sf.lit(" WHERE col3 = 1")
Thanks
func.coalesce('col2', func.lit('')). it will replace the nulls with blank which won't affect the sql string, and the sql will receive it as blank - samkart