向数据库发送信息时出错

时间:2019-01-15 14:55:51

标签: python python-3.x sqlite

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

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

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

1 个答案:

答案 0 :(得分:1)

为此替换您的<dependency> <groupId>org.junit.jupiter</groupId> <artifactId>junit-jupiter-api</artifactId> <version>${junit.jupiter.version}</version> <scope>test</scope> </dependency> <dependency> <groupId>org.junit.jupiter</groupId> <artifactId>junit-jupiter-params</artifactId> <version>${junit.jupiter.version}</version> <scope>test</scope> </dependency> <dependency> <groupId>org.junit.jupiter</groupId> <artifactId>junit-jupiter-engine</artifactId> <version>${junit.jupiter.version}</version> <scope>test</scope> </dependency> ,一切都会正常。

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的{​​{1}}