Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Assign a constant and use it during the SQL querries

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading