Home > database >  Assign a constant and use it during the SQL queries
Assign a constant and use it during the SQL queries

Time:03-02

I am using the pandas to read the data from SQL tables.

Since I have a lot of join and etc computation, I have to use the limit in my code.

So, in multiple lines of my code I have for example, limit 100. How can I assign a constant to put after limit then all of the lines updated and don't need to go over all the lines to update?

For example I assign a constant as a= 100 and then I used the limit a in my code. Here is a simple example which I have with two limits.

feature1 = pd.read_sql("""SELECT * FROM mytable LIMIT 100""", db1)

feature2 = pd.read_sql("""SELECT * FROM mytable LIMIT 100""", db2)

I want something like this:

a = 100
feature1 = pd.read_sql("""SELECT * FROM mytable LIMIT a""", db1)
feature2 = pd.read_sql("""SELECT * FROM mytable LIMIT a""", db2)

Thanks for helping me

CodePudding user response:

I'd suggest using an f-string:

>>> a = 100
>>> print(f"""SELECT * FROM mytable LIMIT {a}""")
SELECT * FROM mytable LIMIT 100

As long as your code controls the value of a, this is safe. It doesn't conflict with general advice against SQL injection. If the value of a comes from an untrusted source, then you should use a query parameter.

  • Related