简体   繁体   中英

Insert value to MySQL Database if not exist using Python(PyMySQL)

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**

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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM