1

I need to insert the logs from my test case into a table in postgresql data base.

I was able to connect to the db but I can't figure out how to insert this line result in the tabble, I have tried the below but it doesnt work

import logging
import psycopg2
from io import StringIO
from config import config
params = config()
conn = psycopg2.connect(**params)
print(conn)
curr = conn.cursor()
try:

        if not hw.has_connection():
            logging.error('Failure: Unable to reach websb! ==> '+ str(driver.find_element_by_xpath('//span[@jsselect="heading" and @jsvalues=".innerHTML:msg"]').text))

            return

        elif hw.is_websiteReachable():
            logging.info("Success: website is reachable!")

            curr.execute("""INSERT INTO db_name(logs) VALUES (%s)""", ("Success: website is reachable!"))
             conn.commit()
  except:
        logging.error("Failure: Unable to reach website!")
        return

Iam a total beginner in this. I have searched but I couldnt find a clear example or guide about it. the above code throws the exception eventhough the website is reachable. sorry if I sound dumb.

2 Answers 2

0

It looks like you're incorrectly constructing your SQL statement. Instead of INSERT INTO db_name(table_name) ... it should be INSERT INTO table_name(column_name) .... If you've correctly connected to the appropriate database in your connection settings, you usually don't have to specify the database name each time you write your SQL.

Therefore I would recommend, the following modification (assuming your table is called logs and it has a column named message):

# ...
sql = 'INSERT INTO logs(message) VALUES (%s);'
msg = 'Success: website is reachable!'
curr.execute(sql, (msg))
conn.commit()

You can read the pyscopg2 docs here for more information as well if that would help with passing named parameters to your SQL queries in Python.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, but Im looking for a way to send the logs from logging directly to the DB, just like the filehandler method but instead to a db
0

You can check a good solution that I personally use in my in-server projects. You just need to give a connection-string to the CRUD object and all the things will be done. For Postgres you can use:

'postgresql+psycopg2://username:password@host:port/database'

or

'postgresql+pg8000://username:password@host:port/database'

for more details check SQLAlchemy Engine Configuration.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.