Sunday, October 15, 2023

Automate SQL Table Creation/Insertion using Python

def createTable():

  global fields, table

  table = input("Enter table name: ")

  s = "CREATE TABLE " + table + "(\n"

  while True:

    attr = input("Enter attribute: ") # Enter empty string to quit

    if attr == '':

      break

    dtype = input("Enter type: ").upper()

    fields[attr] = dtype

    s += '  ' + attr + ' ' + dtype + ',\n'

  s += ');'

  s = s[:-4] + s[-2:]

  print(s)

  out = open("TempTable.txt", 'w')

  out.write(s) # Write CREATE TABLE commands to TempTable.txt

  out.close()


def addRecords():

  global table, fields

  out = open("TempRecords.txt", 'w')

  while True:

    choice = input("Continue inserting? ") # Enter empty string to quit

    if choice == '':

      break

    rec = "INSERT INTO " + table + " VALUES("

    for key in fields.keys():

      s = "Enter " + key + " - " + fields[key] + ": "

      val = input(s)

      dtype = fields[key].upper()[:3]

      if dtype != "INT" and dtype != "DEC" and dtype != "BOO":

        val = "'" + val + "'"

      rec += val + ', '

    rec = rec[:-2] + ");\n"

    out.write(rec) # Write INSERT INTO commands to TempRecords.txt

  out.close()


table, fields = "", {}

while True:

  print("1. CREATE TABLE")

  print("2. INSERT INTO")

  print("0. Exit")

  choice = input("Enter choice: ")

  if choice == '1':

    createTable()

  elif choice == '2':

    addRecords()

  elif choice == '0':

    break

  else:

    print("Wrong choice\n")


No comments:

Post a Comment