首页 > 解决方案 > 向数据库发送信息时出错

问题描述

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

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

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,它将显示有关此人的所有详细信息

标签: pythonpython-3.xsqlite

解决方案


用这个替换你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这是导致此问题的原因,因为您试图将值分配CursorReadOnly


推荐阅读