0

I am working on Databricks and I am trying to pass a python variable into a SQL query:

series_name "LogTest"

query = """SELECT * FROM results_table
  WHERE name = $series_name
  """
spark.sql(query).toPandas()

I tried with $ but it does not work.

How do I do this?

Regards

3
  • 2
    Why not use f-string to format the query? Commented May 29, 2020 at 11:41
  • 1
    look this example :stackoverflow.com/questions/44582450/… Commented May 29, 2020 at 11:43
  • is this a python code? any reason '=' is missing the first line? Commented May 29, 2020 at 11:44

3 Answers 3

1

In this case, your variable and queries are just strings. You can do:

query = f"""SELECT * FROM results_table
WHERE name = '{series_name}'
"""

... in python 3. Remember that your query string needs the single quotes around the inserted variable. However, for certain variables, you may need to pass the variable directly to the spark module so it can interpret it. I use pyodbc a lot and would do this:

query = f"""SELECT * FROM results_table
WHERE name = ?"""
cursor.execute(query, series_name)
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! I tried with f-string but I did not put the single quotes ('). Normally it works without it
1

Following will also work,

series_name = "LogTest"
spark.sql("SELECT * FROM results_table WHERE name = " + series_name).toPandas()

Comments

0

we can also try the following.

series_name = "LogTest"
query = "SELECT * FROM results_table WHERE name = {}".format(series_name)
spark.sql(query).toPandas() #

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.