Search code examples
pythongoogle-bigqueryformatting

Problems querying with python to BigQuery (Python String Format)


I am trying to make a query to BigQuery in order to modify all the values of a row (in python). When I use a simple string to query, I have no problems. Nevertheless, when I introduce the string formatting the query does not work. As follows I'm presenting the same query, but diminishing the number of columns that I am modifying. I already made the connection to BigQuery, by defining the Client, etc (and works properly).

I tried:

"UPDATE `riscos-dev.survey_test.data-test-bdrn` SET informaci_meteorol_gica = {inf}, risc = {ri} WHERE objectid = {obj_id}".format(inf = df.informaci_meteorol_gica[index], ri = df.risc[index], obj_id = df.objectid[index])

To specify the input values in format: df.informaci_meteorol_gica[index] = 'Neu' , also a string for df.risc[index] and df.objectid[index] = 3

I am obtaining the following error message:

BadRequest: 400 Braced constructors are not supported at [1:77]

Solution

  • Instead of using format method of string, I propose you another approach with the f string formating in Python :

    def build_query():
      inf = "'test_inf'"
      ri = "'test_ri'"
      obj_id = "'test_obj_id'"
    
      return f"UPDATE `riscos-dev.survey_test.data-test-bdrn` SET informaci_meteorol_gica = {inf}, risc = {ri} WHERE objectid = {obj_id}"
    
    if __name__ == '__main__':
      query = build_query()
    
      print(query)
    

    The result is :

    UPDATE `riscos-dev.survey_test.data-test-bdrn` SET informaci_meteorol_gica = 'test_inf', risc = 'test_ri' WHERE objectid = 'test_obj_id'
    

    I mocked the query params in my example with :

    inf = "'test_inf'"
    ri = "'test_ri'"
    obj_id = "'test_obj_id'"