In Code2, you can use SQL query as datasource and you can run SQL query as frontend action. Here we explain how to implement common use cases.

Datasource - query by session user

We have a data list where we display user's products. How to implement this in Code2:

  1. Create SQL query as list's datasource

  2. Filter product table by session's userId. Session object is scd. In SQL query, we can write ${scd.userId}. So, our simple query would be

    select * from x_product where user_id=${scd.userId}

Frontend Action - query by page variable

Let's say on sign up page, we would like to query before running sign up action. In Code2, sign up form publishes all its fields to page context. All fields like username and password are published to context as you type.

Let's query user table by page variable email to check if user already exists.

  1. Select Sign Up button and go to Flows tab. Add Execute SQL Query action to "When button is clicked" event. And create new one.

  2. The syntax is still same but we will use req object to access parameters.

    select * from x_user where email='${}'

    IMPORTANT NOTE: Notice we used quotation marks - '${}'. That's because email is text. Previously, we did not use quotation for userId - ${scd.userId}. Because it's integer.

  3. Now, let's actually send that email parameter. Click on settings icon under close button.

  4. Select the source of value as page variable. We can also select component value because email is a text input component.

    You can use any type of source value available. The important thing here is the syntax - ${req.param}. You can send parameters from different sources. And you can access them in SQL query using that syntax.

    That's it! When user clicks the Sign Up button, system queries user table by using page variable email.

Did this answer your question?