Code:
import pyodbc as pyodbc
cnxn = pyodbc.connect(DB_STR)
cursor = cnxn.cursor()
def insert_table(insert_query,date_para):
result = cursor.execute(insert_query,date_para)
cnxn.commit()
The code is used to pass a parameter in sql.
My issue is ,when there is no parameter need to be pass in sql,I still want to reuse insert_table function:
my_query ='''
insert into mytable ...
'''
insert_table(my_query,'')
If I leave the second parameter position empty or add something else there,I will get an error.
How should I modify the code ,so that it can work on both scenarios ,has parameter and has not parameter need to be pass?
If I leave the second parameter position empty or add something else there,I will get an error.
An empty tuple is valid if the query has no parameters:
import pyodbc
connection_string = (
"DRIVER=PostgreSQL Unicode;"
"SERVER=192.168.0.199;"
"UID=scott;PWD=tiger;"
"DATABASE=test;"
)
cnxn = pyodbc.connect(connection_string, autocommit=True)
crsr = cnxn.cursor()
crsr.execute("""\
CREATE TEMPORARY TABLE tmp (
id serial primary key,
txt varchar(50) default '(unknown)')
""")
insert_query = "insert into tmp default values"
date_para = tuple()
crsr.execute(insert_query, date_para)
print(crsr.execute("select * from tmp").fetchall())
# [(1, '(unknown)')]