midrange.com code scratchpad
Name:
generate_SQL.py
Scriptlanguage:
Python
Tabwidth:
4
Date:
05/10/2023 06:07:00 pm
IP:
Logged
Description:
Create a text file of column names in the schema and table specified in the argument list.
The intended purpose is to copy into an SQL statement needing column names, for example a DECLARE CURSOR or INSERT
Code:
  1. #!/usr/bin/env python3
  2. # Generate SQL SELECT statement from a given table
  3. # python3 generate_SQL.py library_name file_name
  4. import ibm_db_dbi as db2
  5. import ibm_db
  6. import sys
  7. import os
  8. import time
  9.  
  10.  
  11. # parameters are schema name and table name
  12. schema = sys.argv[1]
  13. table = sys.argv[2]
  14. qualified_table = schema + "." + table
  15.  
  16.  
  17. # if you want the file name to have a timestamp on it
  18. #ts = time.strftime("%Y%m%d_%H%M%S")
  19. #output_file = "SQL_SELECT_" + ts + ".txt"
  20. output_file = "SQL_SELECT.txt"
  21.  
  22. output_path = "/home/buck/"
  23. full_file = output_path + output_file
  24.  
  25. outfile = open(full_file, "w")
  26.  
  27. # Connect to Db2 for i
  28. dsn = "Database=*LOCAL"
  29. host = "N/A"
  30. conn_options = {ibm_db.SQL_ATTR_AUTOCOMMIT: ibm_db.SQL_AUTOCOMMIT_OFF}
  31. connection = db2.connect(dsn, "", "", host)
  32. cursor = connection.cursor()
  33.  
  34. sql_stmt = """\
  35. select table_name, column_name
  36. from qsys2.syscolumns
  37. where table_name = '""" + table + """'
  38.   and table_schema = '""" + schema + """'
  39. order by ordinal_position;  
  40. """
  41.  
  42. result = cursor.execute(sql_stmt)
  43.  
  44. # TODO error handling
  45. if result == False:
  46.   print('SQL error!')
  47.   print('error ' + db2.stmt_error())
  48.   print('errormsg ' + db2.stmt_errormsg())
  49.   print('messages ' + cursor.messages())
  50.  
  51. outfile.write("select \n")
  52.  
  53. # detail rows
  54. for row , row_value in enumerate(cursor, start=1):
  55.     # debugging
  56.     #print(row_value)
  57.     # append commas to the prior line
  58.     if (row > 1):
  59.        outfile.write(",\n")
  60.     
  61.     qualified_column_name = row_value[0] + '.' + row_value[1]
  62.  
  63.     # write the column
  64.     #outfile.write(qualified_column_name)
  65.     outfile.write(row_value[1])
  66.  
  67. outfile.write("\nFROM " + qualified_table + ";\n")
  68.  
  69. connection.close()
  70.  
  71. outfile.close()
© 2004-2019 by midrange.com generated in 0.01s valid xhtml & css