python - 向数据库发送信息时出错
问题描述
我正在做一个代码,程序要求某人的个人信息,然后他读取这些信息并发送到数据库。所以我可以选择注册和咨询。我不知道程序是否有更多问题,因为我需要先修复它。
当我尝试注册此人时,它给了我错误“无法注册”。我找不到原因。
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
推荐阅读
- django - Views are different but rendering same template
- node.js - 匹配 id 后,有什么方法可以从 MongoDB 数据库中检索 12 条记录?
- php - 为什么我不能在 PHP 中链接图像、CSS 和 favicon
- typescript - Next.js:getServerSideProps 无法将 Next.js 与 Next-redux-wrapper 与 TypeScript 一起使用
- azure - AKS 和 Azure AD 多租户访问
- python - 我想使用列表作为参数从函数的结果中创建一个列表
- google-sheets - Google 表格转到表格快捷方式
- firebase - 如何在 Firestore 规则中访问文档 ID
- javascript - Redux 工具包:createAsyncThunk 操作已分派并返回被拒绝的承诺,该操作返回空有效负载
- java - 如何从java中现有的特定JButton变量中检索字符串值调用?