gpt4 book ai didi

python - 向数据库发送信息时出错

转载 作者:行者123 更新时间:2023-12-01 08:26:31 25 4
gpt4 key购买 nike

我正在编写一个代码,其中程序要求某人提供个人信息,然后他读取这些信息并将其发送到数据库。所以我可以选择注册和咨询。我不知道程序是否还有更多问题,因为我需要先修复它。

当我尝试注册此人时,出现错误“无法注册”。我找不到原因。

import sqlite3
conn = sqlite3.connect('database.db')
c = conn.cursor()

def criardb():
c.execute('CREATE TABLE IF NOT EXISTS pessoas(id INTEGER PRIMARY KEY
AUTOINCREMENT,nome VARCHAR, idade INT, tel VARCHAR, pais VARCHAR)')
conn.commit()
def insertdata(nome,idade,tel,pais):
c.execute = ('INSERT INTO pessoas VALUES (?,?,?,?)',
(nome,idade,tel,pais))
conn.commit()
def consultdata():
sql = c.execute('SELECT * FROM pessoas')
for row in sql:
print("Nome: {}".format(row[0]))
def consultdataind(esc):
sql = c.execute('SELECT * FROM pessoas WHERE id = ?')
for row in sql(sql,(esc)):
print("Nome: {} Idade: {} Telefone: {} País:
{}".format(row[0],int(row[1]),row[2],row[3]))

try:
print("Creating database...")
criardb()

except:
print("ERRO: It was not possible to create the database.")
else:
print("Database successfully created.")

while True:
print("Welcome to the register system, choose a option:")
op = int(input("| 1 - Register | 2 - Consult | 3 - Exit | "))

if op == 1:
n = input("Nome: ")
i = int(input("Idade: "))
t = input("Telefone: ")
p = input("País: ")

try:
insertdata(n,i,t,p)

except:
print("ERRO: It's not possible to register")
else:
print("Successfully registered.")
elif op == 2:
print("List of registered users:")
try:
consultdata()
except:
print("It was not possible to load the list.")

print("Write the person ID to individual consult.")
esc = int(input(">> "))
consultdataind(esc)

elif op == 3:
break
else:
print("Invalid command.")

我需要将所有信息发送到数据库并返回咨询,首先它会显示所有注册的人,然后用户可以在列表中写入某人的相应ID,它将显示有关此人的所有详细信息

最佳答案

用这个替换你的insertdata,一切都会正常工作。

def insertdata(nome,idade,tel,pais):
c.execute('INSERT INTO pessoas (nome,idade,tel,pais) VALUES (?,?,?,?)', [nome,idade,tel,pais])
conn.commit()

这里需要调用游标的execute方法。

顺便说一句,切勿在不指定异常的情况下直接使用 except 。它隐藏了最简单的错误消息,这将使您的代码很难调试。到目前为止,是 AttributeError 导致了此问题,因为您试图将值分配给 Cursor (它是 ReadOnly

)

关于python - 向数据库发送信息时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54201382/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com