如何在数据库上的python中保存输出

时间:2019-06-16 14:48:43

标签: python

我试图将输出保存在postgres数据库中,但是在过程结束时,我只将变量存储在数据库中,而不是将输出结果存储在Python shell中

我能够使用cursor.exexute提交数据库

import psycopg2
from psycopg2 import pool
import random
import urllib
import string

try:
    class Database:

        __connection_pool = None

        @staticmethod
        def initialise(**kwargs):
            Database.__connection_pool = pool.SimpleConnectionPool(1, 10, **kwargs)

        @staticmethod
        def get_connection():
            return Database.__connection_pool.getconn()

        @staticmethod
        def return_connection(connection):
            Database.__connection_pool.putconn(connection)

        @staticmethod
        def close_all_connections():
            Database.__connection_pool.closeall()

    class CursorFromConnectionPool:
        def __init__(self):
            self.conn = None
            self.cursor = None

        def __enter__(self):
            self.conn = Database.get_connection()
            self.cursor = self.conn.cursor()
            return self.cursor

        def __exit__(self, exception_type, exception_value, exception_traceback):
            if exception_value:  # This is equivalent to `if exception_value is not None`
                self.conn.rollback()
            else:
                self.cursor.close()
                self.conn.commit()
            Database.return_connection(self.conn)


    class Web:
        def __init__(self, url_address, shortened_url):
            self.url_address = url_address
            self.shortened_url = shortened_url


        def __repr__(self):
            return format(self.shortened_url)


        def randomString(stringLength = 10):
            """Generate a random string of fixed length """
            url_address = None
            shortened_url = None
            url_address = input("Please enter your url ")

            return ''.join(random.choice(url_address) 
                   for i in range(1, stringLength-1))

        shortened_url = print ("Your Shortened Url is " + "https://www." +  randomString() + ".com" )


    # inserting male list
        def save_to_db(self):
        # This is creating a new connection pool every time!
            with CursorFromConnectionPool() as cursor:
                cursor.execute("INSERT INTO Website (original_url, shortened_url) VALUES (%s, %s)", ( self.url_address, self.shortened_url))


    Database.initialise(database="Learning", user="postgres", password="church75", host="localhost", port=5433)

    user = Web('original_url', 'shortened_url')

    user.save_to_db()

    # user_from_db = User.load_from_db_by_name('sex')

    print("Data inserted successfully, check your database")


except (Exception, psycopg2.Error) as error :
    print ("Unable to insert data into the table ", error)

这就是我得到的

Please enter your url nath.com
Your Shortened Url is https://www.nmcthatm.com
Data inserted successfully, check your database

这就是我在数据库上拥有的

'original_url', 'shortened_url'

0 个答案:

没有答案