如何在Python中插入变量作为文本?



这是我的代码,它是插入数据到数据库中,,如果我使用数字它的工作,但不与文本,我如何解决它?我想我需要把«数据»之间的两个引号",我怎么做?由于

def aggiungi():
print('funzione 'aggiungi'')
conn = db.connect(NOMEDB)
print
"Database aperto con successo";
cognome, nome, indirizzo, mail, tel_fisso, tel_cell = input(
"Inserire cognome, nome, indirizzo, mail, tel_fisso, tel_cell (separati da virgola): ").split(",")
dati = cognome + "," + nome + "," + indirizzo + "," + mail + "," + tel_fisso + "," + tel_cell
conn.execute("INSERT INTO contatti (cognome, nome, "
f"indirizzo, mail, tel_fisso, tel_cell) VALUES ({dati})");

conn.commit()
print ("Records created successfully)")
conn.close()
return

您缺少连接字符串"INSERT INTO contatti (cognome, nome, "f"indirizzo, mail, tel_fisso, tel_cell) VALUES ({dati})"+

然而,我应该指出,这种方法对数据库的安全性是非常危险的,因为它可能被SQL注入攻击。基本上,您是在查询中插入一个通用字符串,而不检查其内容。例如,恶意用户可以为tel_cell添加以下字符串:

3290000000);SELECT * FROM contatti --

这将导致数据库执行恶意用户喜欢的任何查询。

解决方案是准备查询。关于此的进一步阅读:

https://docs.python.org/3/library/sqlite3.html(参见"模块函数和常量"之前的最后一个例子)

https://www.websec.ca/kb/sql_injection

最新更新