1

I am trying to create an Oracle table using Python 3.5. I have the column names and data type stored in a dictionary, and I want to create an SQL statement (stored in sql_stmt) to execute it from Python. My dictionary looks like this:

adict1 = {'col1': 'Number', 'col2': 'Date', 'col3': 'Date'}

I am trying to create an SQL statement which looks like this:

create table dummy(col1 Number, col2 Date, col3 Date)

So, I was trying to create the SQL statement by looping through the dictionary keys:

sql_stmt = "create table"

for key in adict1 :
   sql_stmt = sql_stmt + ("dummy('%s' , '%s')" ,(key,adict1[key]))

But it throws the error:

Traceback (most recent call last):
File "<pyshell#413>", line 2, in <module>
sql_stmt = sql_stmt + ("dumm5('%s' , '%s')" ,(key,adict1[key]))
TypeError: must be str, not tuple

What have I done wrong?

Ollie
  • 1,641
  • 1
  • 13
  • 31
joe
  • 173
  • 3
  • 17
  • 1
    Possible duplicate of [How do I put a variable inside a String in Python?](https://stackoverflow.com/questions/2960772/how-do-i-put-a-variable-inside-a-string-in-python) – Aran-Fey Apr 08 '18 at 08:27

3 Answers3

1

there is a error when you plus the string:

sql_stmt = sql_stmt + ("dumm5('%s' , '%s')" ,(key,adict1[key]))

you can format it like this:

sql_stmt = sql_stmt + 'dumm5({0}, {1})'.format(key, adict1[key])
ryanlee
  • 341
  • 3
  • 9
1

You need to keep the table name and opening bracket outside the loop, make sure the comma is in the right place, use {} and .format to format your string with the variables, remove the last comma, then add the closing bracket.

adict1 = {'col1': 'Number', 'col2': 'Date', 'col3': 'Date'}

sql_stmt = "create table dummy("

for key in adict1 :
   sql_stmt = sql_stmt + ("{} {}, ".format(key,adict1[key]))

sql_stmt = sql_stmt[:-2]
sql_stmt += ")"

Then sql_stmt is "create table dummy(col2 Date, col3 Date, col1 Number)".

Ollie
  • 1,641
  • 1
  • 13
  • 31
0

A more pythonic solution:

adict1 = {'col1':'Number', 'col2':'Date', 'col3':'Date'}
sql_stmt = "create table dummy(%s)" % ', '.join(key+' '+val for key,val in adict1.items())

but it may appear somewhat "over-pythonic"...

sciroccorics
  • 2,357
  • 1
  • 8
  • 21