1

I am trying to Fetch value from an existing database and also insert the value into the database if not exist.

This code works fine to fetch the value the value but I am not able to insert the value into database..

    import pymysql
    connection = pymysql.connect(
    host='localhost',
    user='root',
    password='',
    db='chatbotqad',
    )
    user_input=input('Enter :')
    print(user_input)
    try:
    with connection.cursor() as cursor:
    sql = "SELECT * FROM `qans` WHERE `Questions` = ('%s') " % user_input
    try:
        cursor.execute(sql)
        result = cursor.fetchall()

        if not cursor.fetchone():
            sqli = "INSERT INTO `qans` VALUES (%s)" % user_input
            cursor.execute(sqli) 

        print("Que\t\t Answer")            
        print("-------------------------")            
        for row in result:
            print(str(row[0]) + "\t\t" + row[1])


    except:
        print("Oops! Something wrong")
    connection.commit()
    finally:
    connection.close()**strong text**
2
  • This code is prone to race conditions, ideally you should also add a unique key in your table and also you should do this in one query more or less like INSERT INTO <table> <columns> SELECT <columns> FROM <table> WHERE <condition> .. See the MySQL manual how to use INSERT INTO .. SELECT ... syntax Commented Apr 16, 2019 at 10:43
  • Can you see whether the insert statement is running - e.g. place a print() statement before cursor.execute(sqli) Commented Apr 16, 2019 at 15:03

1 Answer 1

2

I finally found this solution.

import pymysql

connection = pymysql.connect(
    host='localhost',
    user='root',
    password='',
    db='chatbotqad',
)

user_input=input('Enter input:')

try:
    with connection.cursor() as cursor:
        sql = "SELECT * FROM `qans` WHERE `Questions` = ('%s') " % user_input

        try:
            if (cursor.execute(sql)==0):
                result = cursor.fetchall()

                Ans_input=input('Please enter Answer:-')
                sql = "INSERT INTO `qans` (Questions, Answers) VALUES (%s,%s)"

                try:
                    cursor.execute(sql, (user_input,Ans_input))
                    print("Task added successfully")
                except:
                    print("Oops! Something wrong")

            else:
                cursor.execute(sql)
                result = cursor.fetchall()
                print("Que\t\t Answer")
                print("-------------------------")
                for row in result:
                     print(str(row[0]) + "\t\t" + row[1])
        except:
            print("Oops! Something wrong")

    connection.commit()
finally:
    connection.close()
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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