Forezz

postgres

Dec 1st, 2021 (edited)
533
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #python 3.9.5
  2. #pip install psycopg2
  3. #выставлены значения по умолчанию, в аргументах функции create_connection
  4. #можно вбивать свои в таком же порядке в аргументах при запуске из консоли
  5.  
  6. import psycopg2
  7. import sys
  8.  
  9. def create_connection(database="lab6", user="postgres", password="5786", host="127.0.0.1", port="5432"):
  10.   # print([database, user, password, host, port])
  11.   try:
  12.     connection = psycopg2.connect(
  13.       database=database,
  14.       user=user,
  15.       password=password,
  16.       host=host,
  17.       port=port
  18.     )
  19.     print("Database opened successfully\n")
  20.     return connection
  21.   except psycopg2.OperationalError as e:
  22.     print('Unable to connect!\n{0}'.format(e))
  23.     if not str(e):
  24.       print('Check database, user and password')
  25.     # sys.exit(-1)
  26.  
  27. with open('C:\\Users\\vladt\\Desktop\\users.txt') as file:
  28.   users_line = file.readlines()
  29.   if not users_line[-1].endswith('\n'):
  30.     users_line[-1] = users_line[-1] + 'n'
  31.   print(users_line)
  32. users = []
  33. for i in range(len(users_line)):
  34.   users += [users_line[i][:-1].split(',')]
  35. # users += [users_line[i].split(',')]
  36. print(users)
  37.  
  38.  
  39. args = sys.argv[1:]
  40. s = 0
  41. f = 0
  42. for el in users:
  43.   print(el)
  44.   con = create_connection(user=el[0], password=el[1])
  45.   if con:
  46.     s += 1
  47.   else:
  48.     f += 1
  49. print('s=', s, '\nf=', f)
  50. # cur = con.cursor()
  51. # try:
  52. #   cur.execute('''CREAT TABLE a
  53. #        (ADMISSION INT PRIMARY KEY NOT NULL,
  54. #        NAME TEXT NOT NULL,
  55. #        AGE INT NOT NULL,
  56. #        COURSE CHAR(50),
  57. #        DEPARTMENT CHAR(50));''')
  58. #   print("Table created successfully")
  59. # except Exception as e:
  60. #   print(e)
  61. # con.commit()
  62. # con.close()
RAW Paste Data