我正在尝试从现有数据库中获取值,如果还不存在,还将值插入数据库中。
此代码可以很好地获取值的值,但是我无法将值插入数据库。
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**
答案 0 :(得分:0)
我终于找到了解决方案。
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()