0

So i have following rename statement that I want to execute:

"RENAME TABLE `my_table` TO `my_table_temp`, `my_new_table` TO `my_table`,
  `my_table_temp` TO `my_new_table`"

I want to make a function using this query so I could apply it to different tables. The case is that I'm looking for best readable way of formatting string. Tool of choice seems to be .format method and obviously I do not want to make something like this

"RENAME TABLE '{0}' TO '{1}', '{2}' TO '{3}',
  '{4}' TO '{5}'".format('my_table','my_table_temp','my_new_table','my_table','my_table_temp','my_new_table')

But what I do want to make is something like this

.format('my_table','my_table_temp','my_new_table')

and somehow just indicate numbers which should be replaced with each string. Just to be clear - I do not want use 6 arguments for string formatting but just 3 and make each of them be repeated twice in string So I'm seeking an advice of how this should be implemented. Apologize if this question is silly and obvious but I just want to improve my code style to maximum level even in such details before it become too late and I find myself somewhere in gutter, writing awful crap using Python language

3
  • This isn't really a question about MySQL at all, but about standard Python string substitution. This isn't even a parameterized query. Commented Dec 1, 2014 at 10:56
  • There are six format {} braces while you are giving seven input. Commented Dec 1, 2014 at 10:56
  • Using the normal string formatting on an SQL query is dangerous. It can make your application vulnerable to SQL injections: en.wikipedia.org/wiki/SQL_injection . Sometimes you need to use it, but make sure you have no user generated content in the variables you are using. Commented Dec 1, 2014 at 10:58

1 Answer 1

3
In [42]: '{0}, {0}' .format('a')
Out[42]: 'a, a'

In [43]: '{0}, {0}' .format('a', 'b')
Out[43]: 'a, a'

In [44]: '{0}, {1}' .format('a', 'b')
Out[44]: 'a, b'

foramt string works like this.

so you only need to do:-

"RENAME TABLE '{0}' TO '{1}', '{2}' TO '{0}',\  
'{1}' TO '{2}'".format('my_table','my_table_temp',\
                         'my_new_table','my_table')

>>> 
RENAME TABLE 'my_table' TO 'my_table_temp', 'my_new_table' TO 'my_table',  'my_table_temp' TO 'my_new_table'
Sign up to request clarification or add additional context in comments.

1 Comment

@micgeronimo sry i forgot ot edit my solution.I update my answer check it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.